Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the correct type for a click handler when using Svelte with TypeScript?

I am using Svelte with TypeScript. I have a button:

<button on:click|preventDefault={clickHandler}>
   Click me
</button>

I am trying to set the correct type for the click handler.

export let clickHandler: MouseEventHandler<HTMLButtonElement>;

I got MouseEventHandler<HTMLButtonElement> from the TS error when I use a different type, eg:

Type 'Function' is not assignable to type 'MouseEventHandler'.

However this fails with Cannot find name 'MouseEventHandler'. I can't work out where to import the type MouseEventHandler as it's not exported by Svelte.

How do I set the correct type for a click handler when using Svelte with TypeScript?

like image 477
mikemaccana Avatar asked Nov 29 '25 10:11

mikemaccana


1 Answers

Investigating further, Svelte's Event handlers - yes Svelte's not React's - are under svelte.JSX. Yes, when you're using normal .svelte components and not using JSX. I did see JSX references in my research but ignored them because I was not using JSX. But I guess maybe Svelte's TS functionality leverages some existing work from React?

enter image description here

So the correct TS type for a click handler is:

export let clickHandler: svelte.JSX.MouseEventHandler<HTMLButtonElement>;
like image 189
mikemaccana Avatar answered Dec 01 '25 00:12

mikemaccana