What are type-safe event emitters in TypeScript?

Why Interviewers Ask This

Advanced questions like this reveal whether a candidate has internalized TypeScript deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.

Answer

Building a type-safe event emitter in TypeScript ensures that event names and their payload types are connected and validated at compile time. Using a generic event map: type EventMap = { click: MouseEvent; keydown: KeyboardEvent; data: { message: string } };. A typed emitter class: class TypedEmitter<Events extends Record<string, unknown>> { on<K extends keyof Events>(event: K, listener: (data: Events[K]) => void): void { ... } emit<K extends keyof Events>(event: K, data: Events[K]): void { ... } }. Usage: const emitter = new TypedEmitter<EventMap>(); emitter.on("click", (e) => e.clientX); // MouseEvent is known emitter.emit("data", { message: "hello" }); // payload type enforced. Passing a wrong payload type or misspelling an event name produces a compile-time error. Libraries like typed-emitter, eventemitter3 with types, and mitt provide ready-made type-safe event emitters. This pattern is fundamental to building type-safe plugin systems, state management, and component communication.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a TypeScript codebase.