How would you implement a generic type-safe EventEmitter where each event name maps to its own specific payload type?
Short answer
Use a generic type parameter constrained to a mapping object (Record of event names to payload types), and have on()/emit() methods keyed by `keyof EventMap`, so TypeScript enforces that each event's payload argument matches exactly what was declared for that event name.
Advertisement
AModel answer
Use a generic type parameter constrained to a mapping object (Record of event names to payload types), and have on()/emit() methods keyed by `keyof EventMap`, so TypeScript enforces that each event's payload argument matches exactly what was declared for that event name.
type EventMap = { login: { userId: string }; logout: void };
class TypedEmitter<Events extends Record<string, any>> {
private listeners: { [K in keyof Events]?: ((payload: Events[K]) => void)[] } = {};
on<K extends keyof Events>(event: K, handler: (payload: Events[K]) => void) {
(this.listeners[event] ??= []).push(handler);
}
emit<K extends keyof Events>(event: K, payload: Events[K]) {
this.listeners[event]?.forEach(fn => fn(payload));
}
}
const emitter = new TypedEmitter<EventMap>();
emitter.on('login', (payload) => console.log(payload.userId)); // fully typedReal-world example
Building a fully type-safe pub-sub or event bus system where mismatched event names or payload shapes are caught at compile time.
Likely follow-ups
- How would you extend this pattern to support wildcard listeners that receive any event?
Related topics