Event Emitter Generic Typing
What you'll learn: How to use generics to create type-safe event systems where each event name automatically knows its correct payload type.
The Problem with Untyped Event Emitters
In JavaScript, event emitters let you trigger events and attach listeners, but there's no built-in way to ensure that the data you send with "userLoggedIn" matches what the listener expects. You might send a User object but receive it as any, losing all type safety.
Mapping Event Names to Payload Types
Generic event emitters solve this by creating a type mapping: a single generic type parameter that describes which events exist and what data each one carries.
The pattern uses an object type where keys are event names and values are the payload types for those events:
type EventMap = {
userLoggedIn: { userId: string; timestamp: number };
dataFetched: { records: string[] };
error: { message: string };
};
Now your event emitter can use this EventMap as a generic constraint:
class TypedEmitter<Events> {
on<K extends keyof Events>(event: K, handler: (data: Events[K]) => void): void {
// implementation
}
emit<K extends keyof Events>(event: K, data: Events[K]): void {
// implementation
}
}
const emitter = new TypedEmitter<EventMap>();
emitter.on("userLoggedIn", (data) => {
// data is inferred as { userId: string; timestamp: number }
console.log(data.userId);
});
emitter.emit("userLoggedIn", { userId: "123", timestamp: Date.now() });
// emitter.emit("userLoggedIn", { wrong: "shape" }); // Error!
The generic Events type becomes a lookup table. When you call emit("userLoggedIn", ...), TypeScript knows the second argument must match Events["userLoggedIn"].
Key Takeaway: Generic event emitters use a mapped object type to connect event names with their payload types, providing autocomplete, type checking, and self-documenting event contracts across your entire event-driven architecture.