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

Time:10-15

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?

CodePudding user response:

While you can type the property, you might want to just forward the event instead:

<button on:click|preventDefault>
   Click me
</button>

(enter image description here

So the correct TS type for a click handler is:

export let clickHandler: svelte.JSX.MouseEventHandler<HTMLButtonElement>;
  • Related