Skip to content
jshacks.dev
Patterns

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.

1 min read
Summarize in AI

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.

events.tsTypeScript
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);
Text
hello ada

The 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.

Also inTypeScript
Taggednode 24
Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.