javascript / expert
Snippet
Type-Safe Generic Props in Svelte Components
Using the $$Generic helper in Svelte (TypeScript) allows components to operate on polymorphic data structures while maintaining strict type checking for props and logic.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
<script lang="ts">type T = $$Generic<Record<string, any>>;export let items: T[];export let filterKey: keyof T;$: filtered = items.filter(item => item[filterKey]);</script><ul>{#each filtered as item}<li>{item[filterKey]}</li>{/each}</ul>
svelte
Breakdown
1
type T = $$Generic<Record<string, any>>;
Declares a generic type placeholder that will be inferred from the items passed to the component.
2
keyof T
Ensures that the filterKey prop must be a valid property name of the generic type T.
3
$: filtered = ...
Creates a reactive statement that re-runs the filter logic whenever items or filterKey changes.