0
0
Typescriptprogramming~10 mins

Type-safe event emitter pattern in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A[keyof T]
B[keyof T][]
C[event]
D[string]
Attempts:
3 left
💡 Hint
Common Mistakes
Using an array type for the payload parameter.
Using a string type instead of the event key type.
2fill in blank
medium

Complete 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'
A[keyof T]
B[string]
C[number]
D[any]
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic 'any' type for payload.
Using string or number instead of the event key type.
3fill in blank
hard

Fix 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'
Aany
BT[event]
CT[keyof T]
Dunknown
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'any' loses type safety.
Using T[keyof T] is too broad and not specific to the event.
4fill in blank
hard

Fill 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'
A[K]
B[keyof T]
C[event]
D[string]
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.
5fill in blank
hard

Fill 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'
A[event]
B[keyof T]
Cpayload
Devent
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'keyof T' instead of the event variable to index listeners.
Passing 'event' instead of 'payload' to listeners.