03 · TypeScript Type Gymnastics
hardcodingtypescript~25 min

Build a Type-Safe Event Emitter

Objective: Use generics, keyof constraints, indexed access and conditional rest tuples to link an API's arguments.

The emitter below works at runtime but accepts any event name and payload. Type it so that event names and payloads come from an event map. Your code is type-checked with strict mode against hidden assertions. Fix every compiler error and make the assertions pass.

  • TypedEmitter<Events> takes an event map (name → payload type).
  • on(event, handler) infers the handler's payload type and returns an unsubscribe function.
  • emit(event, payload) requires a matching payload; events typed `void` take no payload.
  • Unknown event names and wrong payloads are compile errors.
emitter.emit('login', { user: 'ada' })
→ OK when Events['login'] is { user: string }
TypeScript (strict)

⌘/Ctrl + Enter to type-check · Esc then Tab leaves the editor

Output
> Nothing has run yet.
Interview follow-up questions
  • How would you add once() and off()?
  • Why use a conditional rest tuple instead of an optional payload?
  • How would you type a wildcard '*' listener?