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.
Previous
What is the NoInfer utility type in TypeScript 5.4?
Next
What is the accessor keyword in TypeScript 4.9?
More TypeScript Questions
View all →- Advanced What is structural typing in TypeScript?
- Advanced What are branded types (opaque types) in TypeScript?
- Advanced What is the Variance annotation in TypeScript 4.7?
- Advanced What is the satisfies operator used for in TypeScript?
- Advanced How do you implement a deep partial type in TypeScript?