Projects Blog

How to properly type events handlers in Svelte

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

In the case we want to type an on:click function, we can achieve this by importing MouseEventHandler type:

Button.svelte
<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.

Page.svelte
<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

This is the list of events types, which you can check in their repository:


Using this JSX React 18 typings will could safe type our handlers easily.

I hope you found this article useful.

Happy coding! 🚀

Related posts