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
- Typing Event Maps
- Type-Safe emit and on
- Generic Event Emitter Class
- Inferring Listener Arguments