Skip to content

Instantly share code, notes, and snippets.

@stevekinney
Created February 18, 2024 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevekinney/ab11211d68a12c663d080055b247d0e7 to your computer and use it in GitHub Desktop.
Save stevekinney/ab11211d68a12c663d080055b247d0e7 to your computer and use it in GitHub Desktop.
A fun little utility that I'm looking forward to using in Svelte 5.

Here is a cool thing we can do in Svelte 5 with Runes. Let's say we make a little utility type like this:

type Holocene<T> = T extends { extends: keyof SvelteHTMLElements }
	? Omit<Partial<SvelteHTMLElements[T['extends']]>, keyof T> & Omit<T, 'extends'>
	: T;

Now, we can pass an extends key to the type we give to the props of a component and it will automatically inherit whatever HTML element we choose.

<script lang="ts">
	let { label, id, ...props } = $props<Holocene<{ label: string; extends: 'button' }>>();
</script>

<button {id} {...props}>{label}</button>

Since the utility type is clever about omiting properties, you don't have to worry about dumb collisions (e.g. ClassList is really just a string in practice, but TypeScript doesn't believe that).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment