← All Exercises
Typed Event Emitter with On, Once, and Off
intermediatetypescript
Background
Type-safe emitters catch event-name typos and payload mismatches at compile time. A once subscription must remove itself before invoking the handler so re-entrant emits do not call it twice.
Problem
Implement a TypedEmitter<Events> class with on(event, handler), once(event, handler), and emit(event, payload). Each method must be keyed by the event map so handlers receive the correct payload type, and on/once must return an unsubscribe function. Support removing a subscription before an event fires.
Input
A JSON object with events, each an on, once, off, or emit command with an id or payload.
Output
A JSON array of log lines in the form handlerId:payload, in invocation order.
Sample tests
Sample 1
Input: {"events":[{"type":"on","id":"h1"},{"type":"once","id":"h2"},{"type":"emit","payload":"x"},{"type":"emit","payload":"y"}]}Expected: ["h1:x","h2:x","h1:y"]
Sample 2
Input: {"events":[{"type":"on","id":"h1"},{"type":"off","id":"h1"},{"type":"emit","payload":"x"}]}Expected: []
Sample 3
Input: {"events":[{"type":"once","id":"h2"},{"type":"off","id":"h2"},{"type":"emit","payload":"x"}]}Expected: []
Your solution
Learning objective
Practice generic constraints, keyof indexing, and type-safe publish-subscribe APIs with subscription cleanup.