Skip to content

Commit c17384b

Browse files
committed
improve types for createEventDispatcher
1 parent eb6fb66 commit c17384b

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/runtime/internal/lifecycle.ts

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,29 @@ export function onDestroy(fn: () => any) {
2727
get_current_component().$$.on_destroy.push(fn);
2828
}
2929

30+
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void
31+
? I
32+
: never
33+
34+
type ExtractObjectValues<Object extends Record<any, any>> = Object[keyof Object]
35+
36+
type ConstructDispatchFunction<EventMap extends Record<string, any>, EventKey extends keyof EventMap> =
37+
EventMap[EventKey] extends never
38+
? (type: EventKey) => void
39+
: (type: EventKey, detail: EventMap[EventKey]) => void
40+
41+
type CreateDispatchFunctionMap<EventMap> = {
42+
[Key in keyof EventMap]: ConstructDispatchFunction<EventMap, Key>
43+
}
44+
45+
type EventDispatcher<EventMap extends Record<string, any>> = UnionToIntersection<ExtractObjectValues<CreateDispatchFunctionMap<EventMap>>>
46+
3047
export function createEventDispatcher<
31-
EventMap extends {} = any
32-
>(): <EventKey extends Extract<keyof EventMap, string>>(type: EventKey, detail?: EventMap[EventKey]) => void {
48+
EventMap extends Record<string, any> = any
49+
>(): EventDispatcher<EventMap> {
3350
const component = get_current_component();
3451

35-
return (type: string, detail?: any) => {
52+
return ((type: string, detail?: any) => {
3653
const callbacks = component.$$.callbacks[type];
3754

3855
if (callbacks) {
@@ -43,7 +60,7 @@ export function createEventDispatcher<
4360
fn.call(component, event);
4461
});
4562
}
46-
};
63+
}) as EventDispatcher<EventMap>;
4764
}
4865

4966
export function setContext<T>(key, context: T) {
@@ -59,7 +76,7 @@ export function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T {
5976
}
6077

6178
export function hasContext(key): boolean {
62-
return get_current_component().$$.context.has(key);
79+
return get_current_component().$$.context.has(key);
6380
}
6481

6582
// TODO figure out if we still want to support

0 commit comments

Comments
 (0)