Here's a concept for an event handling system:
type EventMap = Record<string, any>;
type EventKey<T extends EventMap> = string & keyof T;
type EventReceiver<T> = (params: T) => void;
interface Emitter<T extends EventMap> {
on<K extends EventKey<T>>
(eventKey: K, fn: EventReceiver<T[K]>): void;
emit<K extends EventKey<T>>
(eventKey: K, params: T[K]): void;
}
// example usage
const eventHandler = eventEmitter<{
data: Buffer | string;
end: undefined;
}>();
// OK!
eventHandler.on('data', (x: string) => {});
// Error! 'string' is not assignable to 'number'
eventHandler.on('data', (x: number) => {});
The setup functions correctly but I have questions about it:
Why is
EventKey
defined withstring &
?Do we really need generics
K
in theon
andemit
methods or could we simplify them by using justkeyof T
for the type ofeventKey
?
Thank you for your insights.