0Pricing
TypeScript Academy · Lesson

Generic Event Emitter Class

Build a reusable typed event emitter from scratch.

Goal: A TypedEmitter Class

We will build a reusable TypedEmitter<E> class generic over an event map E, with fully typed on, off, and emit methods.

interface Events { login: { userId: string }; logout: void }
// class TypedEmitter<Events> will manage handlers safely.
console.log("building a typed emitter");

A Handler Type Alias

Define a handler type parameterized by the event name so each listener receives the right payload.

type Handler<E, K extends keyof E> = (payload: E[K]) => void;
// E[K] is the payload type for event K in map E.
console.log("handler typed by E[K]");

All lessons in this course

  1. Typing Event Maps
  2. Type-Safe emit and on
  3. Generic Event Emitter Class
  4. Inferring Listener Arguments
← Back to TypeScript Academy