Event type typescript for event handler in Svelte
Asked Answered
L

3

7

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!

Lucarne answered 19/11, 2021 at 7:19 Comment(1)
see also React.MouseEvent<HTMLDivElement> etc here and hereEureetloir
S
13

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

Skip answered 19/11, 2021 at 8:50 Comment(4)
Seem to be it's wrong! Because the base on:keyup type of Svelte is KeyboardEventHandler<HTMLInputElement>. I received the typescript error like this: Type '(event: WithTarget<KeyboardEvent, HTMLInputElement>) => void' is not assignable to type 'KeyboardEventHandler<HTMLInputElement>'Lucarne
You are right, I adjusted my post.Skip
This answer works perfectly. ThanksLucarne
Almost works great for me, I have currently ({ target : { value } }: WithTarget ) => debounce(value) and now defined it as a function const onKeyUp = (event:WithTarget<KeyboardEvent, HTMLInputElement>) => { const target = event.target const value = target?.value debounce(value) } but it complains about target.valuePentameter
P
0

This is the only way I could do it:

const handleKey = (e: CustomEvent) => {

   const event = e as unknown as KeyboardEvent;
   
   if (event.key === 'Backspace') {
      ...
<TextField bind:value on:keyup={handleKey}>

I had to typecast.

J

Phrasal answered 22/12, 2022 at 2:17 Comment(0)
A
0

You can now also type the arrow function variable as KeyboardEventHandler (with HTMLInputElement as the type parameter).

Now:

  • event will be of type KeyboardEvent
  • with event.target of type EventTarget
  • and event.currentTarget typed as EventTarget & HTMLInputElement
const handleKeyUp: KeyboardEventHandler<HTMLInputElement> = (event) => {
  console.log(event) // type KeyboardEvent
  console.log(event.target) // type EventTarget
  console.log(event.currentTarget) // type EventTarget & HTMLInputElement
}

See the difference between target and currentTarget on MDN or on Stack Overflow.

Alexandrite answered 23/8 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.