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?
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?
So the correct TS type for a click handler is:
export let clickHandler: svelte.JSX.MouseEventHandler<HTMLButtonElement>;