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;

Explanation

A typo in an event name or a wrong payload becomes a compile error.

Further reading

Problem with a question

TypeScript · Middle · question 73

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz