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
- Your code has no type errors
- The console prints
hello Ashaanditems 2 - A correct payload is accepted
- A misspelled event name is rejected
- A wrong payload type is rejected
- A handler parameter is typed from the event name
- 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.
Press Run to see the page.
Console
Nothing printed yet.