How to correctly type a custom element event bubbling on the imported component? #10761
Replies: 2 comments
|
There are two distinct problems here — typing a custom event on an HTML element vs. typing it on a Svelte component. They need different module augmentations. For HTML elements (e.g., // app.d.ts or a .d.ts file included in tsconfig
declare module "svelte/elements" {
interface DOMAttributes<T extends EventTarget> {
"on:m-click"?: MeltEventHandler<MouseEvent> | undefined | null;
}
}
export {};Note: For Svelte components (e.g., Svelte components expose events through // In the component's script block or a companion .d.ts
import type { SvelteHTMLElements } from 'svelte/elements';
// For Svelte 5 runes mode — events are just props:
interface Props {
'on:m-click'?: MeltEventHandler<MouseEvent>;
}Root cause of the mismatch: Recommended pattern for Melt UI components specifically: define an |
|
forwarded element events never go through for
so augment that map too export {};
declare global {
interface HTMLElementEventMap {
'm-click': MeltEvent<MouseEvent>;
}
}
declare module 'svelte/elements' {
interface DOMAttributes<T extends EventTarget> {
'on:m-click'?: MeltEventHandler<MouseEvent> | undefined | null;
}
}you need both if you would rather not add a global event interface $$Events {
'm-click': MeltEvent<MouseEvent>;
}that fixes the component side with no global augmentation but checked with |
Uh oh!
There was an error while loading. Please reload this page.
I tried a few things but each doesn't seem to type correctly.
I'm guessing that Svelte is defaulting the type of any
on:${string}as a generic event handler. Is there a way to narrow the type such as when I useon:m-clickon the Button component, it correctly assesses the type as it is in the declare module?All reactions