Recall & Review
beginner
What is a type-safe event emitter pattern?
It is a way to create an event system where the types of events and their data are checked by TypeScript, preventing errors by ensuring only valid events and data are used.
Click to reveal answer
intermediate
Why use TypeScript generics in a type-safe event emitter?
Generics allow defining a map of event names to their data types, so the emitter knows exactly what data each event carries, enabling compile-time checks.
Click to reveal answer
intermediate
How does the listener function signature look in a type-safe event emitter?
It matches the data type of the event it listens to, for example: (data: EventMap[EventName]) => void, ensuring the listener receives the correct data shape.
Click to reveal answer
beginner
What happens if you try to emit an event with wrong data type in a type-safe event emitter?
TypeScript will show a compile-time error, preventing the code from running until the data matches the expected type for that event.
Click to reveal answer
beginner
Give a simple example of defining an event map for a type-safe event emitter.
Example: type EventMap = { login: { userId: string }; logout: undefined }; This maps 'login' event to an object with userId and 'logout' event with no data.
Click to reveal answer
What does a type-safe event emitter ensure?
✗ Incorrect
Type-safe event emitters check event names and data types at compile time to avoid errors.
In TypeScript, how do you define the types of events and their data for a type-safe emitter?
✗ Incorrect
A generic interface or type maps event names to their data types, enabling type safety.
What is the type of the listener function parameter in a type-safe event emitter?
✗ Incorrect
The listener receives the exact data type defined for the event, ensuring type safety.
What happens if you emit an event with incorrect data type in a type-safe event emitter?
✗ Incorrect
TypeScript prevents emitting events with wrong data types by showing errors during compilation.
Which TypeScript feature is essential for creating a type-safe event emitter?
✗ Incorrect
Generics allow mapping event names to data types, enabling type safety.
Explain how a type-safe event emitter works and why it is useful.
Think about how TypeScript checks event names and data before running the program.
You got /4 concepts.
Describe how you would implement a simple type-safe event emitter in TypeScript.
Start with a type for events, then use generics to enforce types in methods.
You got /4 concepts.