typescript · level 3 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A shared kind field tells union members apart.
A union of object types is hard to use if you cannot tell which member you have. Give every member the same property, like kind, holding a different literal type. That property is the , and the whole union is a .
Check the discriminant and TypeScript narrows to exactly one member. A makes this tidy: it compares one value with each in turn and runs the first match. Inside case "card": the checker knows there is a lastDigits.
type Payment = { kind: "card"; lastDigits: string }
| { kind: "cash"; amount: number }
| { kind: "voucher"; code: string };
function describe(payment: Payment): string {
switch (payment.kind) {
case "card":
return `Card ending ${payment.lastDigits}`;
case "cash":
return `£${payment.amount} in cash`;
case "voucher":
return `Voucher ${payment.code}`;
}
}
console.log(describe({ kind: "cash", amount: 20 })); A long union can put each member on its own line, starting with |. A return inside a case leaves the whole function.
guess first
Show a server reply. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Reply = { status: "ok"; data: string }
| { status: "error"; message: string };
function show(reply: Reply): void {
if (reply.status === "ok") {
console.log(reply.data);
} else {
console.log(reply.data);
}
}
show({ status: "ok", data: "Saved!" });
your turn
Your turn. Introduce the animals.
Finish the second case with the fish's kind and its own property, then give the dog a trick and the fish a colour.
fix it
The ticket machine will not start. Fix the switch.
- Read the error: the checker thinks
pricecan reach its end without returning. So whichcaseever matches? switch (ticket)compares the whole object with strings like"child", so nocasecan match. Switch on the discriminant.- On line 3, change
switch (ticket)toswitch (ticket.kind), then run.
nailed it
your unions say exactly which one they are. :D
- Give every union member a discriminant like
kindwith its own value. switchon the discriminant narrows to one member percase.- Each
casecan only read its own member's properties.
new words in your collection
- discriminant
- discriminated union
- switch
- case
This lesson isn’t saved. A free account remembers every lesson you finish.