Discussion: How can we type the events supported by a component
See original GitHub issueThe goal is to easily catch typos and help the discovery of all possible events dispatched by a component. After all, there is no reason why the inputs (props) can have a strong contract but the outputs (events) don’t. In fact, it’s even more important than for props, because the dispatching can occur about anywhere in the file, whereas props are usually neatly bunched together are the top.
Right now I can type on:qoidfoqidjoiqsjd just fine.
Flex, which also had its compiler used custom annotations for this: https://github.com/apache/flex-sdk/blob/master/frameworks/projects/mx/src/mx/core/Container.as#L97
Perhaps we could have a special, reserved convention like export type Events = {name: 'eventA', data: number} | ...
Having the TSDoc carry over on the consumer side tooltip would be the icing on the cake.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:9
- Comments:6 (5 by maintainers)

Top Related StackOverflow Question
You can now take advantage of the
createEventDispatchertyping introduced in Svelte 3.25.0. If you doYou get strong typing for
dispatchwithin the component, and if you listen to thefoo/barevents, you’ll get strong typings:You’ll also get much better autocompletion for events now. Note however that you are still allowed to listen to other events, so type safety in the sense of “only listen to events defined through
createEventDispatcher” is still only possible through theComponentEventsinterface. But we plan on providing something (maybe a script tag attribute) which would make the events strict.Related docs: https://github.com/sveltejs/language-tools/blob/master/docs/preprocessors/typescript.md#typing-component-events
The reason why this cannot be implemented easily is that it’s a lot harder to collect all possible events than to collect the props. That’s also the reason why autocompletion does not work because these are for props.
Looking under the hood it’s that props are implemented through jsx props. Events are not because of the limitations of collecting them. If the user would explicitly type them this could be changed. We cannot mark the dispatched events as “this does not conform to the definition” though because of the challenges mentioned.
Having a reserved interface is likely the way forward. We have thought about this before in the context of generic props. Reserved interface names could be
ComponentEvents,ComponentProps,ComponentSlotsandComponentDeffor typing all three.Related #304