Build a Typed Event Emitter

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write createEmitter<Events>(), where Events maps each event name to its payload type. It returns on(name, handler), which registers a handler and returns a function that removes it, and emit(name, payload), which calls that event's handlers in the order they were added. The types must reject unknown event names and payloads of the wrong type, and give each handler its event's payload type.

Your code must pass

  • Calls an event's handlers in order with the payload
  • Doesn't call other events' handlers
  • Removes a handler with the function on returns
  • Has no type errors
  • Handlers get their event's payload type
  • Rejects an unknown event
  • Rejects the wrong payload