×

typescript · level 3 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An map links each event name to its .

An event is a message that something happened, like a login or a new order. A is a function that runs when its event happens. The data the event carries is its payload. Many apps let any part of the code send events and listen for them.

An is an interface from event names to payload types. With K extends keyof Events, on("order", handler) hands the handler exactly Events["order"]. A misspelt name or the wrong payload is caught at once.

interface Events {
  login: { user: string };
  order: { id: number; total: number };
}
type Handlers = { [K in keyof Events]: ((payload: Events[K]) => void)[] };
const handlers: Handlers = { login: [], order: [] };
function on<K extends keyof Events>(name: K, handler: (payload: Events[K]) => void): void {
  handlers[name].push(handler);
}
function emit<K extends keyof Events>(name: K, payload: Events[K]): void {
  handlers[name].forEach((handler) => handler(payload));
}
on("order", (order) => console.log(`Order ${order.id}: £${order.total}`));
emit("order", { id: 7, total: 30 });

forEach takes a callback and calls it once for every item of an array.