Skip to content

How to type ...props when 'spread' event handlers #11814

Answered by brunnerh
J4gQBqqR asked this question in Q&A
Discussion options

You must be logged in to vote

Depends on how the props are used.
E.g. if they are passed on to an element, you can intersect the declared props with a type from svelte/elements.

import type { HTMLButtonAttributes } from 'svelte/elements';
let {
	icon = "line-md:close",
	button_style = "",
	icon_style = "text-2xl",
	children,
	...props
}: {
	icon: string;
	button_style: string;
	icon_style?: string;
	children?: Snippet;
} & HTMLButtonAttributes = $props();

If you only want to allow events (limited by the prefix on), you can define an index like this:

let { /*...*/ }: {
	icon: string;
	button_style: string;
	icon_style?: string;
	children?: Snippet;
	[key: `on${string}`]: Function;
} = $props();

Expand the types to [key…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by J4gQBqqR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants