What are type-safe event emitters in TypeScript?

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.