Skip to content
jshacks.dev
TypeScript

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.

1 min read
Summarize in AI

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.

emitter.tsTypeScript
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');
Text
welcome Ada

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

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
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

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.