Implement a typed event emitter
Implement a typed event emitter in TypeScript with an event map and generics, so emit and on check payload types. Node.js 24 strips the types.
An event emitter with a map from event names to payload types catches a wrong name or a wrong payload when you compile, not when it runs.
type Events = {
login: { user: string };
logout: undefined;
};
class TypedEmitter<E extends Record<string, unknown>> {
#handlers: { [K in keyof E]?: Set<(payload: E[K]) => void> } = {};
on<K extends keyof E>(event: K, handler: (payload: E[K]) => void): () => void {
(this.#handlers[event] ??= new Set()).add(handler);
return () => {
this.#handlers[event]?.delete(handler);
};
}
emit<K extends keyof E>(event: K, payload: E[K]): void {
this.#handlers[event]?.forEach((handler) => handler(payload));
}
}
const bus = new TypedEmitter<Events>();
bus.on('login', ({ user }) => console.log('hello', user));
bus.emit('login', { user: 'ada' });
bus.emit('logout', undefined);hello adaThe generic K links the event name to its payload. bus.emit('login', { name: 'ada' }) and bus.on('signup', ...) both fail to type-check, and inside the handler for login the argument is known to have a user string. The handlers live in a mapped type with one set per event.
Node.js 24 runs this file as it is by stripping the types, and nothing checks them at run time, so run tsc --noEmit to get the errors. Nothing stops a JavaScript caller from sending the wrong payload.