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
Both mistakes compile. The first never fires the listener. The second fires it with a string, so user.name is undefined and .toUpperCase() throws at runtime.
There are three separate failures hiding here:
Event names are plain strings, so a typo is just another valid string.
Payloads are any, so the compiler cannot check what emit sends or what a listener receives.
Nothing connects the two, so even a correct name gives no information about the matching payload.
A generic event map fixes all three with one declaration.
The event map pattern in one idea
An event map is a type that maps each event name to the payload type of that event:
interface AppEvents {
'user:signed-in': { userId: string; at: Date };
'cart:item-added': { sku: string; quantity: number };
}
The emitter class takes this map as a type parameter. Every method then uses keyof on the map to restrict event names, and an indexed access type on the map to look up the payload for a specific name.
You already rely on this pattern if you write front-end code. TypeScript's own DOM typings use it to type addEventListener. In simplified form, the declaration looks like this:
That is why button.addEventListener('click', (e) => ...) gives you a MouseEvent, while 'keydown' gives you a KeyboardEvent. You are going to apply the same idea to your own events. For background on how the browser API behaves at runtime, see the MDN reference for EventTarget.addEventListener().
Prerequisites and compiler settings
This guide assumes you are comfortable with basic TypeScript syntax. These language features do the heavy lifting, and the official handbook covers each one:
Generics for the type parameter that holds the map.
Turn on strict in your tsconfig.json. Without it, TypeScript relaxes the checks that make this pattern valuable, such as strictFunctionTypes and strictNullChecks. The examples also assume a target of ES2015 or later, because they use Map and Set.
Step 1: Define the event map
Start with the vocabulary of your application. Decide what events exist and what data each one carries:
A few design choices are worth making deliberately:
One payload per event. Each event carries a single value, usually an object. Objects are easy to extend later: you can add an optional field without breaking existing listeners.
void means "no payload". The 'app:ready' event carries nothing. We will make emit('app:ready') work without a second argument in Step 4.
Namespaced names. Prefixes such as user: and cart: keep names readable as the map grows, and they pair well with template literal types later in this guide.
You can write the map with interface or type. The constraint we use in the next step accepts both, which avoids a well-known trap that we will explain there.
Step 2: Build the core of the emitter
Here is the smallest useful version. It only has on and emit, and it assumes every event has a payload:
type Listener<TPayload> = (payload: TPayload) => void;
class TypedEmitter<TEvents extends Record<keyof TEvents, unknown>> {
private readonly listeners = new Map<keyof TEvents, Set<Listener<never>>>();
on<K extends keyof TEvents>(event: K, listener: Listener<TEvents[K]>): void {
let set = this.listeners.get(event) as Set<Listener<TEvents[K]>> | undefined;
if (!set) {
set = new Set();
this.listeners.set(event, set);
}
set.add(listener);
}
emit<K extends keyof TEvents>(event: K, payload: TEvents[K]): void {
const set = this.listeners.get(event) as Set<Listener<TEvents[K]>> | undefined;
set?.forEach((listener) => listener(payload));
}
}
Three details deserve explanation.
The generic constraint.TEvents extends Record<keyof TEvents, unknown> says "TEvents is an object type with whatever keys it has, and each value can be anything." You might expect to write TEvents extends Record<string, unknown> instead. That version fails for interfaces, because TypeScript does not give interfaces an implicit index signature, so AppEvents would be rejected even though it looks like a perfectly good map. Constraining against the type's own keys accepts both interfaces and type aliases.
The method signatures.K extends keyof TEvents captures the specific event name the caller passes. Once TypeScript infers K as, say, 'cart:item-added', the type TEvents[K] resolves to { sku: string; quantity: number }. The listener's parameter and the emit payload are both derived from that single K.
The internal storage and the one cast. The Map stores listeners for many different events in one container, so its value type has to be broad. We use Listener<never>, because a function that accepts never is the supertype every listener can be assigned to. Inside on and emit, we narrow the stored set back to the precise listener type with a cast. This is the boundary where TypeScript cannot prove that a name and its listeners line up. Keeping that single cast private inside the class means the public API stays completely cast-free. If you want to read more about why listener types behave this way, the handbook's discussion of function parameter bivariance and strictFunctionTypes is a good companion.
Step 3: Why a single type parameter K matters
It is tempting to write emit with two independent parameters:
This looks right, but TEvents[keyof TEvents] is the union of every payload in the map. The compiler checks the name against all names and the payload against all payloads, with no link between them:
const loose = new LooseEmitter<AppEvents>();
// Compiles, but the payload belongs to 'user:signed-out', not 'cart:item-added'
loose.emit('cart:item-added', { userId: 'u_42' });
The generic K in the real emitter is what creates the correlation. Both parameters mention the same K, so choosing a name fixes the payload type. This is the same reasoning behind the guidance in our article on TypeScript function overloads vs union parameters: when one argument decides the type of another, a generic parameter usually beats a union.
Here is what the compiler does when you call emit('cart:item-added', { sku: 'A1', quantity: 2 }):
It infers K from the first argument, giving the literal type 'cart:item-added'.
It computes TEvents[K], which is { sku: string; quantity: number }.
It checks the second argument against that type and reports an error if the shapes differ.
No casts, no overloads, and no duplicated declarations are needed.
Step 4: Support events with no payload
With the core emitter, emit('app:ready') fails because a second argument is required. The usual fix is to turn the payload into a rest parameter whose shape depends on the event:
This conditional type returns an empty tuple when the payload is void, and a one-element tuple otherwise. The square brackets around TPayload matter: they stop the conditional from distributing over unions, so a payload of string | undefined is not accidentally treated as void. The label payload: is purely documentation, and it appears in editor tooltips.
Now emit uses it:
emit<K extends keyof TEvents>(event: K, ...args: EmitArgs<TEvents[K]>): void {
const payload = (args as unknown[])[0] as TEvents[K];
// ... call listeners with `payload`
}
Labeled tuples and variadic tuple types arrived in TypeScript 4.0, and rest parameters are covered in the handbook chapter on functions. The result is that events with a payload require exactly one argument, and events without one forbid a second argument.
Step 5: Unsubscribe handles, once, and cancellation
A real emitter needs a way to stop listening. Leaked listeners are a common source of memory growth and of handlers that keep running after their owner is gone. The cleanest API is to have on return an unsubscribe function:
const stop = bus.on('user:signed-in', handle);
// later
stop();
This is also the exact shape that React's useEffect cleanup and useSyncExternalStore expect, which we will use shortly.
Here is the complete implementation, combining everything so far with off, once, an AbortSignal option, a wildcard onAny, and a listenerCount helper for diagnostics:
export type Listener<TPayload> = (payload: TPayload) => void;
export type Unsubscribe = () => void;
export type ListenOptions = { signal?: AbortSignal };
type EmitArgs<TPayload> = [TPayload] extends [void]
? []
: [payload: TPayload];
export type AnyEvent<TEvents> = {
[K in keyof TEvents]: { event: K; payload: TEvents[K] };
}[keyof TEvents];
export class TypedEmitter<TEvents extends Record<keyof TEvents, unknown>> {
private readonly listeners = new Map<keyof TEvents, Set<Listener<never>>>();
private readonly anyListeners = new Set<Listener<AnyEvent<TEvents>>>();
on<K extends keyof TEvents>(
event: K,
listener: Listener<TEvents[K]>,
options: ListenOptions = {},
): Unsubscribe {
const { signal } = options;
if (signal?.aborted) return () => {};
let set = this.listeners.get(event) as Set<Listener<TEvents[K]>> | undefined;
if (!set) {
set = new Set();
this.listeners.set(event, set);
}
set.add(listener);
const off = () => this.off(event, listener);
signal?.addEventListener('abort', off, { once: true });
return off;
}
once<K extends keyof TEvents>(
event: K,
listener: Listener<TEvents[K]>,
options: ListenOptions = {},
): Unsubscribe {
const off = this.on(
event,
(payload) => {
off();
listener(payload);
},
options,
);
return off;
}
off<K extends keyof TEvents>(event: K, listener: Listener<TEvents[K]>): void {
const set = this.listeners.get(event) as Set<Listener<TEvents[K]>> | undefined;
set?.delete(listener);
if (set?.size === 0) this.listeners.delete(event);
}
onAny(listener: Listener<AnyEvent<TEvents>>): Unsubscribe {
this.anyListeners.add(listener);
return () => {
this.anyListeners.delete(listener);
};
}
emit<K extends keyof TEvents>(event: K, ...args: EmitArgs<TEvents[K]>): void {
const payload = (args as unknown[])[0] as TEvents[K];
// Snapshot first, so listeners that unsubscribe during emit don't skip others.
const set = this.listeners.get(event) as Set<Listener<TEvents[K]>> | undefined;
if (set) {
for (const listener of Array.from(set)) listener(payload);
}
if (this.anyListeners.size > 0) {
// One internal cast: TypeScript cannot prove the event/payload correlation for a generic K.
const envelope = { event, payload } as unknown as AnyEvent<TEvents>;
for (const listener of Array.from(this.anyListeners)) listener(envelope);
}
}
listenerCount<K extends keyof TEvents>(event: K): number {
return this.listeners.get(event)?.size ?? 0;
}
}
A few behaviors are intentional and worth knowing:
Snapshot before calling.Array.from(set) copies the listeners before iteration. If a listener unsubscribes itself, which is exactly what once does, the loop is not disturbed. Without the snapshot, adding or removing entries mid-iteration can cause skipped or repeated calls.
Synchronous, in registration order. This matches how the Node.js EventEmitter documents its own behavior: listeners are invoked synchronously in the order they were registered.
Duplicates collapse. Because listeners live in a Set, registering the same function twice for the same event results in one registration. Node allows duplicates. If you need that behavior, store listeners in an array instead.
Cancellation with AbortSignal. Passing a signal lets you tear down many subscriptions at once by aborting a single controller. See MDN's AbortSignal reference for the standard behavior.
Step 6: Use it and watch the compiler work
Create one emitter for the application and use it:
const bus = new TypedEmitter<AppEvents>();
const stop = bus.on('user:signed-in', ({ userId, at }) => {
console.log(`${userId} signed in at ${at.toISOString()}`);
});
bus.emit('user:signed-in', { userId: 'u_42', at: new Date() });
bus.emit('app:ready'); // no payload needed
stop();
Notice that the listener's parameter is destructured with no annotation. TypeScript knows it is { userId: string; at: Date } because the listener type was derived from the event name.
Now the mistakes from the beginning of this guide, as the compiler sees them:
// @ts-expect-error Argument of type '"user:signedin"' is not assignable to the event names
bus.emit('user:signedin', { userId: 'u_42', at: new Date() });
// @ts-expect-error Type 'string' is not assignable to type 'number'
bus.emit('cart:item-added', { sku: 'A1', quantity: '2' });
// @ts-expect-error Expected 2 arguments, but got 1
bus.emit('user:signed-out');
// @ts-expect-error Expected 1 arguments, but got 2
bus.emit('app:ready', {});
Your editor also autocompletes event names inside on and emit, which makes the event map double as living documentation.
Step 7: A wildcard listener that narrows like a discriminated union
Logging, analytics and debugging tools often want to observe every event. The AnyEvent type we defined converts the map into a union of envelopes, one per event:
type AnyEvent<TEvents> = {
[K in keyof TEvents]: { event: K; payload: TEvents[K] };
}[keyof TEvents];
For AppEvents, this produces a union like { event: 'user:signed-in'; payload: {...} } | { event: 'cart:item-added'; payload: {...} } | .... Because event is a literal type in each member, it works as a discriminant, so switch narrows the payload automatically:
bus.onAny((e) => {
switch (e.event) {
case 'user:signed-in':
console.log(e.payload.userId, e.payload.at);
break;
case 'user:signed-out':
console.log(e.payload.userId);
break;
case 'cart:item-added':
console.log(e.payload.sku, e.payload.quantity);
break;
case 'app:ready':
console.log('ready');
break;
default: {
// If you add an event to AppEvents and forget this switch, this line errors.
const unhandled: never = e;
return unhandled;
}
}
});
The exhaustiveness check in the default branch is a useful safety net: adding a new event to the map turns every incomplete wildcard handler into a compile error. For a deeper look at this technique, read our guide to TypeScript discriminated unions and type narrowing.
Alternative design: tuple-based event maps
So far each event carries one payload value. Node.js uses a different convention, where each event maps to the tuple of arguments that listeners receive. That design supports zero, one or many arguments naturally and needs no conditional type:
The labeled tuple elements (jobId, percent) show up as parameter names in editor tooltips. Recent versions of the @types/node package, which is maintained in DefinitelyTyped, also let you pass a map of this tuple shape directly to the built-in class:
import { EventEmitter } from 'node:events';
class JobRunner extends EventEmitter<JobEvents> {}
const runner = new JobRunner();
runner.on('progress', (jobId, percent) => {
console.log(jobId, percent.toFixed(0));
});
runner.emit('finished', 'job_1', 1240);
Check the version of @types/node in your project to confirm it includes the generic EventEmitter. If it does, extending it gives you typed events without writing your own class.
Which convention should you choose?
Question
Payload-object map
Tuple map
Matches Node.js conventions
No
Yes
Easy to add fields later without breaking listeners
Yes
Harder, since order matters
Multiple arguments per event
Wrap in an object
Native
No-payload events
Needs a conditional type
Native (empty tuple)
Works well with a wildcard envelope
Yes
Needs extra mapping
Best fit
Application and UI event buses
Node.js-style modules and streams
For application-level event buses, the object-payload design tends to age better. For modules that mirror Node.js APIs, tuples keep you consistent with the platform.
Compose, extend and augment event maps
Real systems grow in pieces, and the event map should grow with them.
Intersections merge the keys, so keyof PlatformEvents contains all three names. If two maps define the same key with incompatible payloads, the intersection produces an unusable type for that event, so keep event names unique per domain.
This works because interfaces with the same name merge, as described in the handbook's section on declaration merging. One caveat: augmentations apply to the whole compilation, so any file in the program sees every event that any included plugin declares. That is usually what you want, but be aware of it in large monorepos.
Using the emitter in React
An emitter subscription is a side effect, so it belongs in an effect with a cleanup. Because on returns an unsubscribe function, the effect body is a single line:
Storing the handler in a ref means callers can pass inline functions without re-subscribing on every render, and the effect only re-runs when the event name changes. See the React documentation for useEffect for the cleanup rules.
If you are exposing emitter-backed state to components, React also offers useSyncExternalStore, whose subscribe argument expects exactly the "return an unsubscribe function" shape used here. We cover it in detail in useSyncExternalStore explained.
Test your types, not just your runtime
Runtime tests confirm listeners fire. Type tests confirm that wrong code is rejected. The @ts-expect-error directive, introduced in TypeScript 3.9, is ideal for this: it fails the build if the next line does not produce an error.
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { TypedEmitter } from './typed-emitter';
interface TestEvents {
ping: { id: number };
ready: void;
}
test('delivers payloads and supports unsubscribe', () => {
const emitter = new TypedEmitter<TestEvents>();
const seen: number[] = [];
const stop = emitter.on('ping', ({ id }) => seen.push(id));
emitter.emit('ping', { id: 1 });
stop();
emitter.emit('ping', { id: 2 });
assert.deepEqual(seen, [1]);
assert.equal(emitter.listenerCount('ping'), 0);
});
test('once runs a single time', () => {
const emitter = new TypedEmitter<TestEvents>();
let calls = 0;
emitter.once('ready', () => calls++);
emitter.emit('ready');
emitter.emit('ready');
assert.equal(calls, 1);
});
test('rejects invalid usage at compile time', () => {
const emitter = new TypedEmitter<TestEvents>();
// @ts-expect-error unknown event name
emitter.emit('pong', { id: 1 });
// @ts-expect-error wrong payload type
emitter.emit('ping', { id: 'one' });
});
The runtime tests use Node's built-in test runner. Run tsc --noEmit in CI so the type tests execute as part of your normal build. If someone later loosens the emitter's types, an @ts-expect-error line that no longer errors will fail the check and flag the regression.
Runtime concerns that types cannot solve
TypeScript types are erased when your code is compiled, so the event map guarantees nothing about data that arrives from outside your program. Keep these limits in mind:
Validate at the boundary. If an event payload originates from a network response, a message from another window, or user input, the type is a claim, not a check. Validate with a schema library or hand-written guards before calling emit. Our article on type-safe server-driven UI in React shows schema validation at a trust boundary. If you need to turn a sample API response into payload interfaces quickly, the JSON to TypeScript Converter can generate a starting point, and the JSON Formatter & Validator helps you check fixtures before you paste them into tests. Review any generated types by hand before relying on them.
Listener errors. In this implementation, a listener that throws stops the remaining listeners and the exception reaches the caller of emit. That matches Node's synchronous behavior. If you prefer isolation, wrap each call in try/catch and report errors to a handler you control.
Async listeners. A listener typed as returning void can still be an async function. The emitter does not await it, so a rejected promise will not be caught by emit. Node's documentation describes the captureRejections option for its own emitter if you need a reference design.
Listener leaks. Node warns when more than ten listeners are added for a single event by default, because that pattern often signals a leak. Consider adding a similar guard, or use listenerCount in diagnostics. Prefer unsubscribing in cleanup functions or aborting a shared signal.
Re-entrancy. A listener may call emit again, even for the same event. The snapshot-before-iterate approach keeps this predictable, but design events so that recursive emits cannot loop indefinitely.
Mutable payloads. Every listener receives the same object reference. If one listener mutates it, the others see the change. Pass immutable data, or freeze payloads in development.
Common mistakes to avoid
Typing event names as string. Using emit(event: string, ...) throws away the whole benefit. Always constrain names with keyof on the map.
Constraining the map with Record<string, unknown>. Interfaces fail that constraint. Use Record<keyof TEvents, unknown> or accept object.
Two unrelated parameters for name and payload. As shown in Step 3, a union of payloads allows mismatches. Use one generic K.
Casting at call sites. If you find yourself writing as AppEvents['user:signed-in'] when emitting, the map or the emitter is wrong. Fix the types instead of silencing them.
One giant map for everything. Hundreds of events in a single interface hurt readability and editor performance. Split by domain and compose with intersections.
Forgetting to unsubscribe. Always keep the returned function and call it during cleanup.
Using events for request/response. Emitters are for notifications. If a caller needs a result, a typed function call or a promise is clearer than a pair of events.
When not to write your own
A custom class is not always the right call. Consider these alternatives first:
Your code runs only in Node.js and mirrors Node APIs. Extend the built-in EventEmitter with a tuple map if your @types/node version supports it.
You are modeling DOM-style events in the browser.EventTarget and CustomEvent are native, though typing custom events on them takes extra declarations.
You need cross-process or cross-network delivery. An in-memory emitter does not cross process boundaries. You will need a transport, and you should validate payloads at both ends.
Write your own typed emitter when you want a small, dependency-free event bus whose behavior, such as unsubscribe handles, AbortSignal support and a typed wildcard, is exactly what your application needs.
Frequently asked questions
Should the event map be an interface or a type?
Either works with the constraint TEvents extends Record<keyof TEvents, unknown>. Use an interface if you want declaration merging for plugins, and a type alias if you want to build the map with mapped types or intersections.
How do I type an event that sometimes has a payload and sometimes does not?
Model it as a union that includes undefined, such as { id: string } | undefined. The EmitArgs helper treats only void as "no argument", so an undefined member keeps the argument required but allows callers to pass undefined. If the argument should be optional, split it into two events or define a dedicated optional-payload helper.
Does this pattern work with async listeners?
Yes for typing, because a function returning Promise<void> is assignable to a function returning void. The emitter simply does not wait for it. If you need to await all listeners, add an emitAsync method that collects results with Promise.all.
Can I get the payload type of an event outside the emitter?
Yes. Use an indexed access type on the map, for example AppEvents['cart:item-added'], and export helper types such as type Payload<K extends keyof AppEvents> = AppEvents[K] for shared code.
Is a typed emitter slower than an untyped one?
Types are erased at runtime, so the generated JavaScript is the same as for a plain class. The costs you can measure come from your design choices, such as snapshotting listeners on every emit, not from the type annotations.
Conclusion and checklist
A type-safe event emitter is a small amount of code with a large payoff. The central idea is that one declaration, the event map, drives event names, payload types, listener signatures and wildcard handlers. Everything else is careful use of keyof, indexed access types and a single generic parameter that ties a name to its payload.
Use this checklist when you build or review one:
The event map is the single source of truth, with namespaced, unique event names.
The constraint accepts both interfaces and type aliases.
Name and payload share one generic K, with no unions of payloads.
No-payload events work with emit('name'), and extra arguments are rejected.
on returns an unsubscribe function, and once and AbortSignal cancellation are available.
The wildcard listener narrows by event and uses an exhaustive never check.
Type tests with @ts-expect-error run in CI through tsc --noEmit.
Payloads that come from outside your program are validated at the boundary.
Listener counts, errors and async behavior are handled deliberately.
Start with the minimal version from Step 2, add features only when your application needs them, and keep the event map small and domain-focused. Your future self, and every teammate who mistypes an event name, will see the error in the editor instead of in production.
3Docker Sessions Lost After Redeploy? Fix In-Memory Storage