Skip to main content
🟦 TypeScript Projects

What you're building

A typed event bus where every event name is locked to a specific payload type. Unlike a plain EventEmitter, the TypeScript compiler will refuse to subscribe with the wrong callback signature or emit the wrong payload shape.

Requirements

Define EventBus<Events extends Record<string, unknown>> — a class parameterised over a map of { eventName: payloadType }.

  • on<K extends keyof Events>(event: K, handler: (payload: Events[K]) => void): void — subscribe a typed handler.
  • off<K extends keyof Events>(event: K, handler: (payload: Events[K]) => void): void — remove the exact handler reference.
  • emit<K extends keyof Events>(event: K, payload: Events[K]): void — call every handler subscribed to this event with the payload.

Stretch goals

  • Add once<K> that auto-unsubscribes after first fire.
  • Return a dispose function from on for convenient cleanup.

What this proves

You can use mapped/indexed access types (Events[K]) to create APIs that are ergonomic AND type-safe — a pattern used throughout large React, Vue, and Node codebases.

⚡ 50 XP
solution.tsTranspiled & run in your browser
Loading editor…
Tests4 to pass
emit calls the handler with payload
off removes handler so it stops firing
multiple handlers all fire
emit on event with no handlers does nothing

Run your code to check these.