Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 96 ยท Projects

Project: Type-Safe Event Emitter

Build a fully typed event emitter in TypeScript - an event map, mapped listener types, on/off/once, disposable subscriptions, async listeners and type tests.

Event emitters are everywhere: Node's EventEmitter, the browser's addEventListener, message buses, game engines, UI frameworks. They let one part of a program announce "an order was placed" without knowing who is listening. That decoupling is great for design and terrible for safety in plain JavaScript, where nothing checks that the event name is spelled right or that listeners receive the payload they expect.

In this project you'll build an emitter where the compiler checks both. You describe your events once, in a single interface, and from then on every on, once, off and emit call is type-checked: misspell an event and it's a compile error; forget a payload field and it's a compile error; read a property the payload doesn't have and it's a compile error. You'll build it in four stages, each a complete program you can run, and finish with a test suite that checks both behavior and types.

The plan

Stage What you build Main TypeScript ideas
1 on and emit driven by an event map Generic classes, keyof, indexed access E[K], mapped types
2 Unsubscribing, once, off, using subscriptions Returning functions, Disposable, Map keyed by functions
3 Events without payloads, async listeners, error isolation Conditional tuple types, rest parameters, Promise.allSettled
4 A test suite for behavior and types node:assert, Expect<Equal<โ€ฆ>>, @ts-expect-error as a test

Stage 1: an event map drives everything

The key design decision is the event map: an interface whose keys are event names and whose values are payload types.

TypeScript
interface ShopEvents {
  'user:signedUp': { userId: number; email: string };
  'order:placed': { orderId: string; userId: number; totalCents: number };
  'order:shipped': { orderId: string; carrier: string };
}

The emitter is generic over that map, EventEmitter<E>. Each method has its own type parameter K extends keyof E, the event name, and uses the indexed access type E[K] for that event's payload. When you call emit('order:shipped', โ€ฆ), TypeScript infers K as 'order:shipped', so the payload must be E['order:shipped'].

Listeners are stored in a mapped type: for every key K of E, an optional Set of listeners for E[K]. The storage is typed per event, so a listener for one event can never end up in another event's set.

TypeScript Stage 1: a typed on and emit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output can't show what the compiler knows: inside the second listener, order has the type { orderId: string; userId: number; totalCents: number }, inferred through contextual typing from Listener<E['order:placed']>. Listeners run in the order they were added, which is why the receipt prints before the stock reservation.

The constraint E extends object keeps the class flexible: any interface or object type works as an event map. (A tighter constraint like Record<string, unknown> would reject interfaces, because interfaces don't have an implicit index signature.)

Now the payoff. This program makes three typical mistakes. It fails on purpose:

TypeScript Mistakes the emitter catches (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Nothing runs, and the compiler explains each problem:

TEXT
main.ts(24,11): error TS2345: Argument of type '"order:place"' is not assignable to parameter of type 'keyof ShopEvents'.
main.ts(25,28): error TS2741: Property 'carrier' is missing in type '{ orderId: string; }' but required in type '{ orderId: string; carrier: string; }'.
main.ts(26,54): error TS2339: Property 'total' does not exist on type '{ orderId: string; totalCents: number; }'.

In plain JavaScript, all three bugs would run silently: the misspelled event would reach no listener, the shipping email would say "on its way with undefined", and the receipt would print undefined. Here, they can't even be compiled. Editors also autocomplete event names from keyof ShopEvents, so most of these mistakes are never typed in the first place.

Stage 2: unsubscribing, once and using

Listeners must be removable, or long-running programs leak memory and keep reacting to events after they should have stopped. This stage adds three ways to remove a listener:

  • on returns a Subscription with an unsubscribe() method. Holding on to it is the easiest way to clean up later.
  • off(event, listener) removes a listener by reference, the way removeEventListener does.
  • once(event, listener) removes itself after the first call.

The subscription is also a Disposable: it has a [Symbol.dispose]() method. That makes it work with using declarations (using Declarations and Explicit Resource Management): a subscription declared with using inside a block is removed automatically when the block ends, even if the block throws.

To support once and off together, the storage changes from a Set of listeners to a Map from each listener to its options. off can then remove any listener with one delete, whether it was added with on or once.

TypeScript Stage 2: off, once and disposable subscriptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each removal technique shows up in the output: A-2 has no audit line, the survey runs only for the first shipment, the second low-stock alarm never fires, and the report listener counts A-3 but not A-4. Some details worth noticing:

  • interface Subscription extends Disposable. Disposable is a built-in interface (from lib.esnext) that requires a [Symbol.dispose](): void method. Extending it is all using needs.
  • #add is a private method (# methods are real JavaScript private methods). It keeps on and once one line each.
  • The copy in emit ([...map]) prevents surprises when a listener unsubscribes itself or adds a new listener during an emit, which is exactly what once does. Node's EventEmitter behaves the same way.
  • listenerCount(event: keyof E) doesn't need its own type parameter, because it doesn't care about the payload type. A generic is only useful when it links two or more types together, here the event name and the listener's parameter.

Stage 3: no-payload events, async listeners and errors

Three real-world needs remain:

  1. Events without payloads. Some events carry no data ('app:ready', 'cart:cleared'). Forcing callers to write emit('app:ready', undefined) is ugly. With a conditional type on a rest parameter, the payload argument disappears for events whose payload type is void:

    TypeScript
    type EmitArgs<T> = [T] extends [void] ? [] : [payload: T];
    emit<K extends keyof E>(event: K, ...args: EmitArgs<E[K]>): void;
    

    For 'app:ready': void, ...args is the empty tuple [], so emit('app:ready') is the only valid call. For object payloads it's a one-element tuple. The brackets in [T] extends [void] stop the conditional from distributing over unions.

  2. Error isolation. If one listener throws, the others should still run, and the error should go somewhere useful instead of crashing the caller of emit. The emitter takes an onError callback in its options.

  3. Async listeners. A listener that saves to a database returns a promise. emitAsync waits for all listeners with Promise.allSettled and reports how many failed.

TypeScript Stage 3: void events, async listeners and error isolation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the output from top to bottom. emit('app:ready') takes no payload at all. During each emitAsync, the throwing analytics listener is reported through onError while the receipt, database and fraud listeners still run, and the huge order adds a second failure from the async fraud check. emitAsync returns only after every async listener has finished, so the failure count is accurate.

Two type-level details make this work:

  • Listener<T> uses the same EmitArgs<T> as emit, so a listener for a void event takes no parameters and a listener for 'order:placed' takes the order. Calling listener(...args) type-checks because both sides use the same tuple type.
  • The listener return type is void | Promise<void>, so both sync and async listeners fit. In emit, a returned promise gets a .catch so its rejection is reported instead of becoming an unhandled rejection. This is the bug that typescript-eslint's no-floating-promises rule exists to catch.

An alternative design describes every event as a tuple of arguments: interface Events { move: [x: number, y: number]; ready: [] }, with emit<K extends keyof E>(event: K, ...args: E[K]). It supports several arguments per event and needs no conditional type, but payload objects are easier to extend later (adding a field doesn't change every listener's parameter list). Node's own typings for EventEmitter support the tuple style.

Stage 4: testing behavior and types

An emitter is infrastructure: many parts of a program will depend on it, so it deserves tests. Two kinds are needed:

  • Behavior tests check what happens at runtime: order of calls, once, off, error isolation. The small test helper from Tooling and node:assert/strict are enough.
  • Type tests check that the types are exactly right. Positive type tests use Expect<Equal<A, B>> from Built-in Utility Types. Negative type tests use // @ts-expect-error: each one asserts "this line must not compile". If a future change makes the emitter too permissive (say, emit starts accepting any string), the directive is unused and the build fails with error TS2578.

The negative type tests live in a function that is never called, so their code never runs. They exist only for the compiler.

TypeScript Stage 4: the emitter with behavior and type tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

All five behavior tests pass, and the fact that the program ran at all means every type test passed: the three Expect lines evaluated to true, and each of the five @ts-expect-error lines really was an error. Try breaking the emitter on purpose to see the tests catch it:

  • Loosen emit's signature to emit(event: keyof E, ...args: unknown[]) (the call inside then needs a cast). The three payload checks ({ n: '1' }, a missing payload, a payload for reset) stop being errors, and the compiler reports error TS2578: Unused '@ts-expect-error' directive. for each of them. The unknown event name is still caught, because keyof E survived the change.
  • Remove the if (options.once) block, and the once test fails at runtime.
  • Change EmitArgs to [payload: T] for every type, and the _voidEvents type test fails with TS2344: Type 'false' does not satisfy the constraint 'true'. The behavior tests that call emit('reset') break too, with TS2554: Expected 2 arguments, but got 1.

Ideas for extending the emitter

  • Add waitFor(event) that returns Promise<E[K]> resolving with the next payload (a once listener wrapped in a promise), plus an optional AbortSignal to cancel waiting.
  • Support namespaced listening with template literal types, such as onPrefix('order:', โ€ฆ) receiving every order:* event (Template Literal Types).
  • Add a maxListeners warning, like Node's, to detect listener leaks.
  • Make emit return boolean (were there any listeners?) and add eventNames(): (keyof E)[].

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With emit<K extends keyof E>(event: K, payload: E[K]) and E = ShopEvents, what is the payload type of emit('order:shipped', โ€ฆ)?

    TypeScript infers K from the event argument as the literal 'order:shipped', so E[K] is exactly that event's payload type.
  2. 2. What is EmitArgs<void> if type EmitArgs<T> = [T] extends [void] ? [] : [payload: T];?

    void extends void, so the conditional picks the empty tuple, and emit(event, ...args) takes no payload argument for that event.
  3. 3. Why does emit loop over a copy of the listener map ([...map])?

    Removing or adding entries during iteration can skip listeners or call new ones in the same emit. A snapshot gives predictable behavior.
  4. 4. A test file contains // @ts-expect-error above emitter.emit('pong', {}). Someone changes emit to accept any string. What happens?

    @ts-expect-error requires an error on the next line. When the error disappears, the directive itself becomes an error, so it works as a negative type test.
  5. 5. What lets using sub = emitter.on(...) remove the listener at the end of the block?

    using requires a Disposable value. The Subscription interface extends Disposable, and its Symbol.dispose method calls unsubscribe.

Summary

  • Describe events once in an event map interface; a generic EventEmitter<E> with K extends keyof E and E[K] types every call from it.
  • A mapped type ({ [K in keyof E]?: Map<Listener<E[K]>, โ€ฆ> }) keeps each event's listeners correctly typed in storage.
  • Return a subscription from on; make it Disposable so using removes listeners automatically, and support off and once.
  • A conditional rest-parameter type ([T] extends [void] ? [] : [payload: T]) removes the payload argument for events without data.
  • Isolate listener errors with try/catch and an onError hook, attach .catch to returned promises, and use Promise.allSettled for emitAsync.
  • Test behavior with node:assert, positive types with Expect<Equal<โ€ฆ>>, and negative types with @ts-expect-error in a function that never runs.

Next: Project: State Machine