A simple type function to get the correct event type for a Builtin HTML element in Svelte.
To install dependencies:
bun install svelte-html-event
<script lang="ts">
import type { SvelteHTMLElementEvent } from 'svelte-html-event';
function onClick(e: SvelteHTMLElementEvent<'button', 'on:click'>) {
console.log(e.detail);
}
</script>
<button on:click={onClick}>Click me</button>
Also, you can use custom attributes as well.
This is really useful when you use use:
directive by some libraries like svelte-dnd-action.
For Svelte Custom Elements, you can use the builtin SvelteCustomElementEvent
instead.
<script lang="ts">
import type { ComponentEvents } from 'svelte';
import Component from './Component.svelte';
function handleCloseEvent(event: ComponentEvents<Component>['close']) {
console.log(event.detail);
}
</script>
<Component on:close={handleCloseEvent} />
This article inspired me to create this package.
MIT