Skip to content
TypeScript types · Senior · about 20 minutes

A typed event emitter

Write the type TypedEmitter<Events>, where Events maps each event name to its payload type. It has two methods: on(event, listener) and emit(event, payload). The event must be a key of Events. The listener receives that event's payload type, and emit requires that event's payload type. Make each method generic over the key: on<K extends keyof Events>(…).

Start from

// Events maps an event name to its payload type.
type TypedEmitter<Events> = {
  on(event: string, listener: (payload: any) => void): void;
  emit(event: string, payload: any): void;
};

Hints and solution

Solve it in the app: its tests run without a year.

The hints, the solution and what an interviewer looks for opens with a year in the app. What a year includes