typescript · level 3 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two events, one payload short. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Events {
saved: { file: string };
deleted: { file: string; byUser: string };
}
function emit<K extends keyof Events>(name: K, payload: Events[K]): void {
console.log(name, payload);
}
emit("saved", { file: "notes.txt" });
emit("deleted", { file: "old.txt" });
your turn
Your turn. Send two game events.
A player joins, then scores. Fill in a player name, the name of the second event, and some points.
fix it
The typing event is lost. Can you fix it?
- Read the error:
TS2353names a property on line 9 that thetypingpayload does not have. - Compare the payload on line 9 with
typingin the event map. Two letters are swapped. - Change
formtofromon line 9, then run.
nailed it
your events carry exactly the right data. :D
- An event map links every event name to its payload type.
K extends keyof Eventschecks the name;Events[K]checks the payload.- Handlers receive the exact payload type, with no guessing.
new words in your collection
- event
- handler
- payload
- event map
This lesson isn’t saved. A free account remembers every lesson you finish.