Typed Event Emission in Svelte with Generics #15610
Replies: 1 comment
-
As you've written your Props type for the List component, the component can only infer the element's type through strong typing of the function you provide as the Try: <List onchange={(e: string) => (selected = e)}>
{#each simpleArray as item}
<ListItem {item}>
<p>Item {item}</p>
</ListItem>
{/each}
</List> Also, unrelated but I figured I should say: If you do custom events in all lowercase, your names might collide with standard events. Sure, you currently have no issues, but if in the future you want to spread props onto an HTML element, that might cause a problem. My personal decision has been to use camel casing for all custom events. Anyway, back on topic: Let me know if my proposal fixed your issue. |
Beta Was this translation helpful? Give feedback.
-
Hello everyone,
While upgrading my components to use the new Generics syntax (Svelte Docs), I ran into an issue:
I have two components:
However, I am currently getting a type unknown for my onchange parameter.
It looks like the type is not correctly infered because of the usage of the setContext/getContext.
Here’s how I’m using these components:
Is there a way to specify the expected type in Svelte, ensuring that the onchange event correctly infers the type of the selected item?
Something like
<MyComponent<string>>
or another generic-friendly syntax that I may not be aware of?Any guidance would be greatly appreciated!
Here’s a reproducible sandbox:
https://codesandbox.io/p/github/Kayoshi-dev/sample/main
Beta Was this translation helpful? Give feedback.
All reactions