Designing Type-Safe Event Emitters with Generic Event Maps in TypeScript

A typo in an event name is one of the quietest bugs in JavaScript. You write emit('userSignedin'), your listener waits for 'userSignedIn', and nothing happens. There is no exception, no warning and no failing test. You only find out when a feature quietly stops working.

TypeScript can remove this entire class of bug at compile time, and the technique is small: describe your events once in a generic event map, then let the emitter's method signatures derive everything else from that map. This guide walks through the design step by step. You will build a typed emitter from scratch, handle events with no payload, return unsubscribe functions, add a wildcard listener that narrows like a discriminated union, and extend the map across modules. You will also learn when to skip your own class and use the typed EventEmitter that Node.js types already support.

By the end you will understand not just the code, but why each type is written the way it is, so you can adapt the pattern to your own project.

Why untyped event emitters fail silently

Node.js ships a classic EventEmitter, and browsers have EventTarget. Both identify events by string and carry payloads that TypeScript cannot check on its own. Here is the problem in its simplest form:

import { EventEmitter } from 'node:events';

const emitter = new EventEmitter();

emitter.on('userSignedIn', (user) => {
  // `user` is implicitly `any`: no autocomplete, no checking
  console.log(user.name.toUpperCase());
});

emitter.emit('userSignedin', { name: 'Ada' }); // typo: the listener never runs
emitter.emit('userSignedIn', 'Ada');           // wrong payload: runtime crash