Skip to main content
InterviewHubPRO
Section Overview
Q36

Question 36 of 50

Part 3: Enterprise Architecture, Compiler Internals & Performance (Senior / Staff)

72%
TypeScript Master (50 Qs)•Part 3: Enterprise Architecture, Compiler Internals & Performance (Senior / Staff)

How do you build a strongly-typed Event Emitter?

senior LevelCode ExampleFormsPerformanceSystem Design

In Simple Words: By mapping event names to their payload types, you can enforce that emit and on require exact payload signatures:

typescript
type EventMap = {
  login: { userId: string; timestamp: number };
  logout: { userId: string };
  error: { code: number; message: string };
};

class TypedEventEmitter {
  on<K extends keyof EventMap>(event: K, listener: (data: EventMap[K]) => void) {}
  emit<K extends keyof EventMap>(event: K, data: EventMap[K]) {}
}

const emitter = new TypedEventEmitter();
emitter.emit("login", { userId: "123", timestamp: Date.now() }); // Valid
// emitter.emit("logout", { foo: "bar" }); // Compile error!