When we use Svelte with TypeScript, typing event handling functions could suppose some challenges at first. In this post we will explore one potential solution.
Svelte, under the hood, uses types definitions base on JSX React 18 typings for HTML. Importing these types, available at svelte/elements
, can resolve our needs.
Typing an on:click
"undefined" anchor link
In the case we want to type an on:click
function, we can achieve this by importing MouseEventHandler
type:
<script lang="ts"> import type { MouseEventHandler } from 'svelte/elements';
export let handleClick: MouseEventHandler<HTMLButtonElement>;</script>
<button on:click={handleClick}> <slot /></button>
And now, when importing the component and passing a handleClick
function as a parameter, we ensure type safety.
<script lang="ts"> import Button from './Button.svelte';
function handleClick(e: MouseEvent) { const target = e.target; console.log(target); }</script>
<Button handleClick={handleClick} />
Complete list of types"undefined" anchor link
This is the list of events types, which you can check in their repository:
AnimationEventHandler
ChangeEventHandler
ClipboardEventHandler
CompositionEventHandler
DragEventHandler
FocusEventHandler
FormEventHandler
GamepadEventHandler
KeyboardEventHandler
MessageEventHandler
MouseEventHandler
PointerEventHandler
ToggleEventHandler
TouchEventHandler
TransitionEventHandler
UIEventHandler
WheelEventHandler
Using this JSX React 18 typings will could safe type our handlers easily.
I hope you found this article useful.
Happy coding! 🚀