Typed event emitters in forty lines of TypeScript

We wanted an event emitter where the editor knows every event name and payload. It turned out to be forty lines.

Start with the platform

The event loop explains nearly every "it works on my machine" bug we see. Long tasks block input, and a promise chain does not make heavy work any lighter.

type Events = {
  saved: { id: number };
  failed: { id: number; reason: string };
};

export class Emitter<E extends Record<string, unknown>> {
  private handlers: { [K in keyof E]?: Array<(payload: E[K]) => void> } = {};

  on<K extends keyof E>(name: K, handler: (payload: E[K]) => void): void {
    (this.handlers[name] ??= []).push(handler);
  }

  emit<K extends keyof E>(name: K, payload: E[K]): void {
    this.handlers[name]?.forEach((handler) => handler(payload));
  }
}

const bus = new Emitter<Events>();
bus.on('failed', ({ reason }) => console.warn(reason));

We reach for a library when the problem has sharp edges that someone else has already sanded down: date maths, rich text, and anything involving drag and drop. The snippet above is the whole thing; the version in our repository only adds tests.

Shipping less script

  • Prefer a data attribute over a framework component
  • Break long tasks into chunks of under 50 ms
  • Load third-party scripts after interaction
  • Type the public API even in plain JavaScript

4 comments on “Typed event emitters in forty lines of TypeScript”

  1. We tried something similar last year and gave up halfway. Seeing it laid out step by step makes me want to try again.

Leave a comment

Your email address will not be published. Required fields are marked *