Type a generic event emitter
Describe events as a map from name to argument tuple, so on and emit check names and payloads. A small typed emitter for TypeScript 5.
An emitter that takes a string name and any arguments accepts every typo. A map of events to argument lists lets the compiler check both.
type Events = {
login: [user: string];
logout: [];
};
class Emitter<E extends Record<string, unknown[]>> {
private handlers = new Map<keyof E, Array<(...args: any[]) => void>>();
on<K extends keyof E>(event: K, handler: (...args: E[K]) => void): void {
const list = this.handlers.get(event) ?? [];
list.push(handler);
this.handlers.set(event, list);
}
emit<K extends keyof E>(event: K, ...args: E[K]): void {
this.handlers.get(event)?.forEach((handler) => handler(...args));
}
}
const bus = new Emitter<Events>();
bus.on('login', (user) => console.log(`welcome ${user}`));
bus.emit('login', 'Ada');
bus.emit('logout');welcome AdaEach event name maps to a tuple of its arguments, so bus.emit('login') without a user is an error and bus.on('login', ...) gives user the type string. The generic K ties the event name to its payload through E[K]. The handler list uses any[] internally, which is the one place the types are loosened, and the public methods stay strict.
logout has no handler in this run, so it prints nothing. For an emitter on Node.js, EventEmitter accepts the same kind of map as a type argument in @types/node, so check that before writing your own.