JavaScript and TypeScript course ยท Module 10: TypeScript in Practice

Type-safe Event System in TypeScript

9 min read ยท
In this lesson5

In Jurassic Park every system has to react to events immediately: an alarm about escaped raptors, a change in fence status, a new dinosaur position. Such an event system requires precision, because you cannot send temperature data to a handler that expects GPS coordinates. A plain emitter accepts any string and any data, so a typo in an event name silently loses an alarm. TypeScript lets you build a fully typed event system in which the compiler guards correctness for you.

EventMap - Event Type Map

The foundation of a type-safe event system is the EventMap: an interface that maps event names to the types of their data (payload). Names like dinosaur:escaped are ordinary string keys, and the colon groups them:

// Defining the park event map
interface ParkEventMap {
  'dinosaur:escaped': { species: string; paddock: string; dangerLevel: number };
  'fence:status': { zone: string; voltage: number; active: boolean };
  'visitor:enter': { visitorId: string; gate: string; timestamp: Date };
  'visitor:exit': { visitorId: string; gate: string; timestamp: Date };
  'alert:weather': { type: 'storm' | 'heat' | 'flood'; severity: 1 | 2 | 3 };
}

// TypeScript knows the exact shape of data for each event
// 'dinosaur:escaped' => { species: string; paddock: string; dangerLevel: number }
// 'fence:status' => { zone: string; voltage: number; active: boolean }

The interface itself generates no code. It is a contract that every method of the emitter will rely on.

Generic EventEmitter with TypeScript

Now the generic emitter. The T parameter is the event map, and every method has its own K extends keyof T parameter, that is, the name of a single event, so T[K] means exactly the payload of that event:

// Generic EventEmitter - T is the event map
class TypedEventEmitter<T extends Record<string, any>> {
  private listeners: {
    [K in keyof T]?: Array<(data: T[K]) => void>;
  } = {};

  on<K extends keyof T>(event: K, handler: (data: T[K]) => void): void {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event]!.push(handler);
  }

  off<K extends keyof T>(event: K, handler: (data: T[K]) => void): void {
    const handlers = this.listeners[event];
    if (handlers) {
      const index = handlers.indexOf(handler);
      if (index > -1) handlers.splice(index, 1);
    }
  }

  emit<K extends keyof T>(event: K, data: T[K]): void {
    const handlers = this.listeners[event];
    if (handlers) {
      [...handlers].forEach(handler => handler(data)); // copy: once() removes a handler during the loop
    }
  }

  once<K extends keyof T>(event: K, handler: (data: T[K]) => void): void {
    const wrapper = (data: T[K]) => {
      handler(data);
      this.off(event, wrapper);
    };
    this.on(event, wrapper);
  }
}

emit iterates over a copy of the handler array, because once removes its wrapper during the loop, and on the original array the next handler would be skipped. The class knows no concrete events, it reads everything from the map. The exclamation mark in this.listeners[event]! is a non-null assertion: you tell the compiler that the array definitely exists, because you created it one line earlier.

Let us plug in the park map. The data parameter in a handler needs no annotation, because TypeScript infers its type from the event name:

// Usage with ParkEventMap
const parkEvents = new TypedEventEmitter<ParkEventMap>();

// TypeScript knows the handler parameter type - auto-complete works!
parkEvents.on('dinosaur:escaped', (data) => {
  // data is of type { species: string; paddock: string; dangerLevel: number }
  console.log(`ALARM! ${data.species} escaped from ${data.paddock}!`);
  console.log(`Danger level: ${data.dangerLevel}`);
});

parkEvents.on('fence:status', (data) => {
  // data is of type { zone: string; voltage: number; active: boolean }
  if (!data.active) {
    console.log(`Fence in zone ${data.zone} deactivated!`);
  }
});

In the first handler, autocomplete suggests species, paddock and dangerLevel, and in the second one completely different fields.

A call to emit takes the event name and an object that matches it. See what the compiler does with incorrect calls:

// Correct emissions
parkEvents.emit('dinosaur:escaped', {
  species: 'Velociraptor',
  paddock: 'B-7',
  dangerLevel: 5
});

// Compilation error! Missing field 'dangerLevel'
// parkEvents.emit('dinosaur:escaped', { species: 'T-Rex', paddock: 'A-1' });

// Compilation error! Unknown event
// parkEvents.emit('dinosaur:sleeping', { species: 'Stegosaurus' });

A missing field and an unknown event name are compilation errors, not silent failures in a running park. That is the main advantage over an untyped emitter.

Pattern: Strongly-typed addEventListener

In TypeScript's DOM type definitions, addEventListener is typed precisely thanks to event maps such as HTMLElementEventMap. Let us build our own version of this pattern, starting with the map and the base class:

// Event map for a UI component
interface UIEventMap {
  click: { x: number; y: number; target: string };
  hover: { x: number; y: number; element: string };
  keypress: { key: string; code: number; ctrl: boolean; shift: boolean };
  resize: { width: number; height: number };
  scroll: { scrollTop: number; scrollLeft: number };
}

// Component class with typed events
class UIComponent<Events extends Record<string, any> = UIEventMap> {
  private eventHandlers: Map<keyof Events, Set<Function>> = new Map();

  addEventListener<K extends keyof Events>(
    type: K,
    listener: (event: Events[K]) => void
  ): void {
    if (!this.eventHandlers.has(type)) {
      this.eventHandlers.set(type, new Set());
    }
    this.eventHandlers.get(type)!.add(listener);
  }

  removeEventListener<K extends keyof Events>(
    type: K,
    listener: (event: Events[K]) => void
  ): void {
    this.eventHandlers.get(type)?.delete(listener);
  }

  protected dispatchEvent<K extends keyof Events>(
    type: K,
    event: Events[K]
  ): void {
    this.eventHandlers.get(type)?.forEach(handler => {
      (handler as (event: Events[K]) => void)(event);
    });
  }
}

The default parameter = UIEventMap means a regular component knows the basic events right away, and dispatchEvent is protected, so only the component itself sends events.

A map extended with extends adds the park map events, and the derived class passes it as a type parameter:

// Extended component with custom events
interface MapComponentEvents extends UIEventMap {
  'marker:click': { markerId: string; lat: number; lng: number };
  'zone:select': { zoneId: string; name: string };
}

class ParkMapComponent extends UIComponent<MapComponentEvents> {
  selectZone(zoneId: string, name: string): void {
    this.dispatchEvent('zone:select', { zoneId, name });
  }

  clickMarker(markerId: string, lat: number, lng: number): void {
    this.dispatchEvent('marker:click', { markerId, lat, lng });
  }
}

// Usage
const parkMap = new ParkMapComponent();

parkMap.addEventListener('marker:click', (event) => {
  // event: { markerId: string; lat: number; lng: number }
  console.log(`Clicked marker ${event.markerId} at ${event.lat}, ${event.lng}`);
});

parkMap.addEventListener('click', (event) => {
  // event: { x: number; y: number; target: string }
  console.log(`Clicked at ${event.x}, ${event.y}`);
});

parkMap knows both its own events (marker:click) and the inherited ones (click), and every handler gets the right type.

Middleware Pattern with Typed Events

An advanced pattern is middleware that processes an event before it reaches the handler, like an airlock in front of a paddock. reduceRight builds the chain from the end, so the middleware runs in the order of registration:

// Middleware type - processes event and decides whether to pass it through
type EventMiddleware<T> = (
  data: T,
  next: (data: T) => void
) => void;

class MiddlewareEventEmitter<T extends Record<string, any>> {
  private listeners: { [K in keyof T]?: Array<(data: T[K]) => void> } = {};
  private middleware: { [K in keyof T]?: Array<EventMiddleware<T[K]>> } = {};

  on<K extends keyof T>(event: K, handler: (data: T[K]) => void): void {
    if (!this.listeners[event]) this.listeners[event] = [];
    this.listeners[event]!.push(handler);
  }

  use<K extends keyof T>(event: K, mw: EventMiddleware<T[K]>): void {
    if (!this.middleware[event]) this.middleware[event] = [];
    this.middleware[event]!.push(mw);
  }

  emit<K extends keyof T>(event: K, data: T[K]): void {
    const mws = this.middleware[event] || [];
    const handlers = this.listeners[event] || [];

    // Building the middleware chain
    const chain = mws.reduceRight(
      (next: (data: T[K]) => void, mw: EventMiddleware<T[K]>) => {
        return (d: T[K]) => mw(d, next);
      },
      (finalData: T[K]) => {
        handlers.forEach(h => h(finalData));
      }
    );

    chain(data);
  }
}

// Example: logging and validating events
const securitySystem = new MiddlewareEventEmitter<ParkEventMap>();

// Logging middleware
securitySystem.use('dinosaur:escaped', (data, next) => {
  console.log(`[LOG] Escape event: ${data.species}`);
  next(data);
});

// Danger level escalation middleware
securitySystem.use('dinosaur:escaped', (data, next) => {
  if (data.species === 'T-Rex' && data.dangerLevel < 5) {
    next({ ...data, dangerLevel: 5 }); // Escalation!
  } else {
    next(data);
  }
});

securitySystem.on('dinosaur:escaped', (data) => {
  console.log(`Final alert: ${data.species}, danger: ${data.dangerLevel}`);
});

securitySystem.emit('dinosaur:escaped', {
  species: 'T-Rex',
  paddock: 'A-1',
  dangerLevel: 3 // Will be escalated to 5 by middleware
});

The second middleware raises the T-Rex danger level to 5 before the handler sees it, and the original object stays untouched thanks to the spread.

Extracting Event Types (Utility Types for Events)

Finally, some helper types. EventsWithField combines a mapped type with a conditional type: A extends B ? X : Y works like an if in the world of types, that is, it checks the input type, evaluates the extends condition and returns X or Y:

// Utility types for working with event maps
type EventNames<T> = keyof T & string;
type EventPayload<T, K extends keyof T> = T[K];
type EventHandler<T, K extends keyof T> = (data: T[K]) => void;

// Extracting handler for a specific event
type ParkEscapeHandler = EventHandler<ParkEventMap, 'dinosaur:escaped'>;
// (data: { species: string; paddock: string; dangerLevel: number }) => void

// Union type of all payloads
type AnyParkPayload = ParkEventMap[keyof ParkEventMap];

// Filtering events by payload type
type EventsWithField<T, Field extends string> = {
  [K in keyof T]: Field extends keyof T[K] ? K : never;
}[keyof T];

type EventsWithVisitorId = EventsWithField<ParkEventMap, 'visitorId'>;
// 'visitor:enter' | 'visitor:exit'

You can combine a conditional type with infer to extract part of a type, for example type Return<T> = T extends (...args: any) => infer R ? R : never returns the result type of a function.

A type-safe event system is a pattern that works everywhere: from monitoring systems in Jurassic Park to React frontends, Node.js backends and microservices. A generic TypedEventEmitter with an EventMap gives you full type safety, because the compiler makes sure that you emit and listen to exactly the data you declared. I recommend keeping the event map in a single file: it is the best documentation of communication in the system. In the editor below you will build an event monitoring system, and in the next lesson you will take TypeScript to the server with Node.js.

Remember: the event map is the frequency plan of the park radio, thanks to which every ranger hears only messages in the format they expect.

Code for this lesson: index.ts
// Type-safe Event System in TypeScript
// Jurassic Park - Event Monitoring System

// 1. EventMap - map of event types
interface ParkEventMap {
  'dinosaur:escaped': { species: string; paddock: string; dangerLevel: number };
  'fence:status': { zone: string; voltage: number; active: boolean };
  'visitor:enter': { visitorId: string; gate: string };
  'alert:weather': { type: 'storm' | 'heat' | 'flood'; severity: 1 | 2 | 3 };
}

// 2. Generic TypedEventEmitter
class TypedEventEmitter<T extends Record<string, any>> {
  private listeners: { [K in keyof T]?: Array<(data: T[K]) => void> } = {};

  on<K extends keyof T>(event: K, handler: (data: T[K]) => void): void {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event]!.push(handler);
  }

  off<K extends keyof T>(event: K, handler: (data: T[K]) => void): void {
    const handlers = this.listeners[event];
    if (handlers) {
      const idx = handlers.indexOf(handler);
      if (idx > -1) handlers.splice(idx, 1);
    }
  }

  emit<K extends keyof T>(event: K, data: T[K]): void {
    const handlers = this.listeners[event];
    if (handlers) {
      handlers.forEach(h => h(data));
    }
  }

  once<K extends keyof T>(event: K, handler: (data: T[K]) => void): void {
    const wrapper = (data: T[K]) => {
      handler(data);
      this.off(event, wrapper);
    };
    this.on(event, wrapper);
  }
}

// 3. Utility types for events
type EventNames<T> = keyof T & string;
type EventPayload<T, K extends keyof T> = T[K];
type EventHandler<T, K extends keyof T> = (data: T[K]) => void;

// 4. System test
const parkEvents = new TypedEventEmitter<ParkEventMap>();

// Registering handlers with full type safety
parkEvents.on('dinosaur:escaped', (data) => {
  // TypeScript knows: data = { species, paddock, dangerLevel }
  console.log(`ALARM! ${data.species} escaped from ${data.paddock}!`);
  console.log(`   Danger level: ${data.dangerLevel}/5`);
});

parkEvents.on('fence:status', (data) => {
  const status = data.active ? 'ACTIVE' : 'OFFLINE';
  console.log(`Fence ${data.zone}: ${status} (${data.voltage}V)`);
});

parkEvents.on('visitor:enter', (data) => {
  console.log(`Visitor ${data.visitorId} entered through gate ${data.gate}`);
});

parkEvents.once('alert:weather', (data) => {
  console.log(`Weather alert (once): ${data.type}, severity ${data.severity}`);
});

// Emitting events
console.log("=== Jurassic Park Event System ===\n");

parkEvents.emit('visitor:enter', {
  visitorId: 'VIS-042',
  gate: 'Main'
});

parkEvents.emit('fence:status', {
  zone: 'Raptor Paddock',
  voltage: 15000,
  active: true
});

parkEvents.emit('dinosaur:escaped', {
  species: 'Velociraptor',
  paddock: 'B-7',
  dangerLevel: 4
});

parkEvents.emit('alert:weather', {
  type: 'storm',
  severity: 2
});

// The second alert will not trigger the handler (once!)
parkEvents.emit('alert:weather', {
  type: 'heat',
  severity: 1
});

console.log("\n--- The second weather alert was not handled (once) ---");

// The following would NOT compile in TypeScript:
// parkEvents.emit('dinosaur:escaped', { species: 'T-Rex' }); // Missing paddock and dangerLevel!
// parkEvents.emit('unknown:event', {}); // Unknown event!

console.log("\n=== Type-safe events work! ===");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is an EventMap in the context of a type-safe event system?

  2. 2. What advantage does a generic TypedEventEmitter<T> provide compared to an untyped emitter?

Hands-on tasks in the game

  • Code editor

    Implement a generic TypedEventEmitter with the on, emit, and off methods.

  • Code editor

    Create an EventMap with typed payloads and register handlers.

  • Horizontal ordering

    Arrange the elements of an emit call in a typed emitter:

  • Vertical ordering

    Arrange the steps of evaluating conditional type T extends U ? X : Y:

  • Horizontal ordering

    Arrange the elements of a conditional type with infer:

  1. QuestionEventMap in TypeScript
  2. QuestionGeneric EventEmitter
  3. Coding taskExercise: Typed Event Emitter
  4. Coding taskExercise: EventMap and Event Handlers
  5. Put in orderEmit Method Syntax in TypedEventEmitter
  6. Put in orderReview: Evaluating a Conditional Type
  7. Put in orderReview: infer Syntax

Useful articles