Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a type-safe event emitter interface.
Typescript
interface EventEmitter<T> {
on(event: keyof T, listener: (payload: T[1]) => void): void;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using an array type for the payload parameter.
Using a string type instead of the event key type.
✗ Incorrect
The listener function receives the payload of the event type T indexed by the event key.
2fill in blank
mediumComplete the code to define a type-safe emit method.
Typescript
emit(event: keyof T, payload: T[1]): void; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic 'any' type for payload.
Using string or number instead of the event key type.
✗ Incorrect
The payload type must match the event key's type in T.
3fill in blank
hardFix the error in the listener type to ensure type safety.
Typescript
on(event: keyof T, listener: (payload: [1]) => void): void; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'any' loses type safety.
Using T[keyof T] is too broad and not specific to the event.
✗ Incorrect
Using T[event] ensures the listener receives the correct payload type for the event.
4fill in blank
hardFill both blanks to define a type-safe event emitter class.
Typescript
class TypedEmitter<T> implements EventEmitter<T> { private listeners: { [K in keyof T]?: Array<(payload: T[1]) => void> } = {}; on(event: keyof T, listener: (payload: T[2]) => void): void { if (!this.listeners[event]) { this.listeners[event] = []; } this.listeners[event]!.push(listener); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'keyof T' instead of the mapped type variable K.
Using 'event' or 'string' which are not valid index types here.
✗ Incorrect
The listeners object uses mapped types with K in keyof T, so the payload type is T[K].
5fill in blank
hardFill all three blanks to implement the emit method with type safety.
Typescript
emit(event: keyof T, payload: T[1]): void { const eventListeners = this.listeners[2]; if (eventListeners) { eventListeners.forEach(listener => listener([3])); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'keyof T' instead of the event variable to index listeners.
Passing 'event' instead of 'payload' to listeners.
✗ Incorrect
The listeners are accessed by event key, and each listener is called with the payload.