typescripttypessveltesvelte-3

Event type typescript for event handler in Svelte


I'm using Typescript inside my svelte project, I need to define strong type for my event. But I can't find any way to do that.

<script lang="ts">
  const onKeyUp = (event: [type here]) => {
    console.log({ event })
    // const {target, keyCode} = event
  }
</script>
<input type="text" on:keyup={onKeyUp} />

Anyone can help me!


Solution

  • In your case you are looking for the KeyboardEvent type. If you additionally want to type your target, you need to cast it inside your function body. The reason is that it's not possible to statically know that the event handler is on the same element as the one that dispatched the event, so the typings err on the side of caution (see https://github.com/sveltejs/language-tools/issues/579 for more info). So the solution looks something like this:

    <script lang="ts">
      const onKeyUp = (event: KeyboardEvent) => {
        // ...
        (event.target as HTMLInputElement)...;
      }
    </script>
    <input type="text" on:keyup={onKeyUp} />
    

    What you can determine is the currentTarget, for which you can create your own helper type:

    export type WithTarget<Event, Target> = Event & { currentTarget: Target };
    

    usage:

    <script lang="ts">
      import type { WithTarget } from './path/to/your/types/file.ts';
      const onKeyUp = (event: WithTarget<KeyboardEvent, HTMLInputElement>) => {
        // ...
      }
    </script>
    <input type="text" on:keyup={onKeyUp} />
    

    In general, TypeScript comes with a standard lib of interfaces which define the possible DOM events, which are modelled after MDN's event description, like this one: https://developer.mozilla.org/de/docs/Web/API/KeyboardEvent