TypeScript · Middle · Question 73 of 75
How do you implement a type-safe event emitter?
type Events = { login: { userId: string }; logout: undefined };
on<K extends keyof Events>(event: K, cb: (payload: Events[K]) => void): void;- ✓Correct answer: Describe events in a map type and use a generic key so the payload type follows the event name
- 2Use
stringevents andanypayloads - 3Event emitters can't be typed
Explanation
A typo in an event name or a wrong payload becomes a compile error.