Command Palette

Search for a command to run...

Hectal
Phase 7: Generics
TypeScript · Exercise 6 of 6 Previous
Advanced

Build a Typed Event Emitter

The Emitter below works, but its handlers and payloads are any: nothing checks that "login" carries a { user }, and a typo in an event name goes unnoticed.

Make it generic: Emitter<Events extends object>. The event name is K extends keyof Events, and the payload is Events[K] in both on and emit. Keep the AppEvents map. Remove any.

What Check tests

  1. Your code has no type errors
  2. The console prints hello Asha and items 2
  3. A correct payload is accepted
  4. A misspelled event name is rejected
  5. A wrong payload type is rejected
  6. A handler parameter is typed from the event name
  7. No any

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Console

Nothing printed yet.