Skip to content
jshacks.dev
TypeScript

How to Write a Type-Safe Event Emitter

Build a small event emitter in TypeScript where event names and payloads are checked at compile time, using an event map, generics, and mapped tuple types.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Node.js and npm logos.

An event emitter lets one part of a program announce that something happened and another part react, without either holding a reference to the other. The emitter in Node.js and the browser's EventTarget work well, but their types are loose: an event name is a string and a payload is any, so a typo or a wrong argument compiles and fails later. This post builds a small emitter of about thirty lines where the event names and their payloads are checked by the compiler. It is aimed at readers who know basic TypeScript generics, and it uses TypeScript 6.x on Node 26 LTS. The behavior is identical in the TypeScript 7 native compiler, tsgo. For the untyped original, see the Node.js events documentation.

What goes wrong without types

Here is a minimal untyped emitter, so we can see the problem.

TypeScript
class Loose {
  private handlers = new Map<string, Array<(...args: any[]) => void>>();

  on(event: string, handler: (...args: any[]) => void): void {
    const list = this.handlers.get(event) ?? [];
    list.push(handler);
    this.handlers.set(event, list);
  }

  emit(event: string, ...args: any[]): void {
    for (const handler of this.handlers.get(event) ?? []) {
      handler(...args);
    }
  }
}

const bus = new Loose();
bus.on("user:login", (name: string) => console.log(`hi ${name}`));
bus.emit("user:logn", 42);
Text
(no output)

That program prints nothing. The event name is misspelled, the payload is the wrong type, and the handler never runs. No error appears anywhere. This is the bug a typed emitter exists to prevent.

Step 1: Describe events in a map

Start by writing down which events exist and what each one carries. A type alias is the clearest form, with the payload as a tuple of arguments.

TypeScript
type AppEvents = {
  "user:login": [name: string];
  "user:logout": [];
  "cart:add": [sku: string, quantity: number];
};

Each key is an event name. Each value is a tuple of the arguments the handler receives. Tuples let an event carry zero, one or several values, and the labels such as name show up in editor hints. This map is the single source of truth, and the rest of the emitter is generic over it.

Step 2: Make the emitter generic over the map

Now write the class. The type parameter Events is the map, and the constraint says every value must be an array.

TypeScript
type EventMap = Record<string, unknown[]>;

type Handler<Args extends unknown[]> = (...args: Args) => void;

class Emitter<Events extends EventMap> {
  private handlers: { [K in keyof Events]?: Array<Handler<Events[K]>> } = {};

  on<K extends keyof Events>(event: K, handler: Handler<Events[K]>): void {
    const list = this.handlers[event] ?? [];
    list.push(handler);
    this.handlers[event] = list;
  }

  emit<K extends keyof Events>(event: K, ...args: Events[K]): void {
    for (const handler of this.handlers[event] ?? []) {
      handler(...args);
    }
  }
}

Three pieces are doing the work. The generic K is inferred from the event name you pass, so it becomes a literal such as "cart:add". Events[K] looks up the tuple for that name. And the rest parameter ...args: Events[K] spreads the tuple into positional parameters, so an emit call reads like a normal function call.

Declare the map with type, not interface. An interface lacks the implicit index signature that a type alias has, so Emitter<AppEvents> would fail the Record<string, unknown[]> constraint.

Step 3: Use it

Create an instance, register handlers, and emit.

TypeScript
const bus = new Emitter<AppEvents>();

bus.on("user:login", (name) => console.log(`hi ${name}`));
bus.on("cart:add", (sku, quantity) => console.log(`${quantity} x ${sku}`));
bus.on("user:logout", () => console.log("bye"));

bus.emit("user:login", "Ada");
bus.emit("cart:add", "A-100", 2);
bus.emit("user:logout");
Text
hi Ada
2 x A-100
bye

The handler parameters need no annotation. Inside the "user:login" handler, name is a string, because the compiler resolved K from the first argument and looked up the tuple. Hover over quantity and it says number.

Step 4: See the errors it prevents

The mistakes from the untyped version are now compile errors. First, the misspelled event name.

TypeScript
bus.emit("user:logn", 42);
Text
index.ts(1,10): error TS2345: Argument of type '"user:logn"' is not assignable to parameter of type 'keyof AppEvents'.

The wrong payload type is caught too.

TypeScript
bus.emit("cart:add", "A-100", "two");
Text
index.ts(1,32): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

A missing argument is an error.

TypeScript
bus.emit("cart:add", "A-100");
Text
index.ts(1,1): error TS2554: Expected 3 arguments, but got 2.

And a handler with the wrong shape is rejected on registration.

TypeScript
bus.on("user:login", (name: number) => console.log(name));
Text
index.ts(1,22): error TS2345: Argument of type '(name: number) => void' is not assignable to parameter of type 'Handler<[name: string]>'.
  Types of parameters 'name' and 'args_0' are incompatible.
    Type 'string' is not assignable to type 'number'.

These four errors are the whole reason to bother. Each one used to be a silent run-time failure.

Step 5: Add off and once

A real emitter needs a way to unsubscribe, and a way to listen once. Return a function from on, which is easier to use than a separate off call because the caller does not have to keep the handler reference. Here is the complete class.

TypeScript
type EventMap = Record<string, unknown[]>;
type Handler<Args extends unknown[]> = (...args: Args) => void;

export class Emitter<Events extends EventMap> {
  private handlers: { [K in keyof Events]?: Set<Handler<Events[K]>> } = {};

  on<K extends keyof Events>(event: K, handler: Handler<Events[K]>): () => void {
    const set = this.handlers[event] ?? new Set();
    set.add(handler);
    this.handlers[event] = set;
    return () => set.delete(handler);
  }

  once<K extends keyof Events>(event: K, handler: Handler<Events[K]>): () => void {
    const off = this.on(event, (...args) => {
      off();
      handler(...args);
    });
    return off;
  }

  emit<K extends keyof Events>(event: K, ...args: Events[K]): void {
    for (const handler of [...(this.handlers[event] ?? [])]) {
      handler(...args);
    }
  }
}

A Set replaces the array, so unsubscribing is a constant-time delete and adding the same handler twice does not duplicate it. Emit iterates over a copy, so a handler that unsubscribes itself, as once does, cannot disturb the loop. Try it.

TypeScript
const bus = new Emitter<AppEvents>();
const off = bus.on("user:login", (name) => console.log(`hi ${name}`));
bus.once("user:login", (name) => console.log(`first login: ${name}`));

bus.emit("user:login", "Ada");
off();
bus.emit("user:login", "Grace");
console.log("done");
Text
hi Ada
first login: Ada
done

The second emit prints nothing, since the first handler was removed and the second ran once.

When to use the built-in emitter instead

Node.js has events.EventEmitter, and recent @types/node versions let you type it by passing an event map as a generic argument. If your code already runs on Node.js and needs its features, such as error event semantics and captureRejections, use that with a typed map. Write your own when the code runs in a browser, when you want an emitter with no dependency, or when you need the unsubscribe-function style. The browser EventTarget is another option, and its typing is covered in the post on typing event handlers.

Common mistakes

The first mistake is declaring the event map as an interface and tripping the index signature constraint. Use a type alias. The second is mutating the handler list while emitting, which skips handlers. Iterate over a copy. The third is forgetting to unsubscribe, which keeps objects alive and is the usual cause of leaks in long-lived emitters. The fourth is having an async handler throw: emit does not await handlers, so a rejected promise is unhandled. Decide whether emit is fire-and-forget, and document it. The fifth is using one emitter for everything. Several small emitters, each with a short map, are easier to understand than one global bus.

Testing the emitter

An emitter is a good first target for tests, because it has no dependencies and a small surface. Write one test for ordering, which asserts that handlers run in the order they were added. Write one for unsubscribing, which asserts that the function returned by on stops further calls. Write one for once, which asserts that a second emit does not call the handler again. And write one for a handler that unsubscribes itself during an emit, which is the case the copy in emit exists to protect.

The type-level behavior deserves a test as well, and a plain unit test cannot give it. Keep a small file of calls that must not compile, mark each with a @ts-expect-error comment, and run tsc --noEmit in your pipeline. If a refactor makes one of those calls valid, the directive becomes an unused one and the compiler reports it, so the test fails for the right reason. We keep these files next to the code they protect, because the errors they guard against, a misspelled name or a wrong argument, are the reason the emitter exists.

Design choices worth making deliberately

Decide what happens when a handler throws. In the version above, an exception in one handler stops the loop, and later handlers do not run. For application events that is often wrong, and wrapping each call in try and catch with a reporting hook keeps one bad listener from silencing the rest. Decide whether handlers run synchronously, as here, or are scheduled with a microtask, which makes emit return before handlers run and changes the ordering other code can rely on. Decide whether event names are strings, as here, or symbols, which avoid collisions across libraries. None of these choices changes the typing technique, and each one is easier to make before the first caller depends on the behavior.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

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