svelte-html-event Svelte Themes

Svelte Html Event

A simple type function to extract the event types of a built-in HTML element in Svelte

svelte-html-event

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

Usage

<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} />

Inspiration

This article inspired me to create this package.

License

MIT

Top categories

Loading Svelte Themes