Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Product type
- A record or struct: every value holds all of its fields.
- Sum type
- A type whose values are each exactly one of several alternatives, each with its own fields.
- Tag (discriminant)
- The part of a sum value that says which alternative it is, such as kind or the enum variant.
- Exhaustive match
- Handling every alternative of a closed type. Supported exhaustiveness checks can flag a missing case; an ordinary Go interface/type switch does not supply that closed set.
- Catch-all
- A default, _ or generic branch that handles every alternative not named before it.
All the parts, or one of the alternatives
A record combines fields: every value has all of them. A sum chooses: every value is exactly one alternative, with its own fields and a tag that says which. Code that ignores the tag, or catches every remaining alternative at once, treats different things alike.
These forms compose: a receipt can always contain a customer and an item, while the item selects one payload shape. A product combines the parts; a sum distinguishes the possible kinds.
A TypeScript discriminated union gives each alternative a literal tag. Checking that tag narrows the payload type inside a branch. The union describes the accepted shapes statically; external data still needs validation.
01Combinations and alternatives
A record has every field; a sum is one alternative
A café till must turn receipt items into charges, reconcile the day’s sales and refunds separately from tips, then compare card outcomes with the payment totals.
The till first joins the customer record with the item being priced. A weighed item needs a weight and rate, while a counted item needs a count and unit price. Trace which payload each receipt selects and predict both prices.
type Sale =
| { kind: "weighed"; grams: number; perKilo: number }
| { kind: "counted"; count: number; each: number };
type Receipt = { customer: string; sale: Sale };
function price(sale: Sale): number {
switch (sale.kind) {
case "weighed":
return (sale.grams * sale.perKilo) / 1000;
case "counted":
return sale.count * sale.each;
}
}
const receipts: Receipt[] = [
{ customer: "Ana", sale: { kind: "weighed", grams: 500, perKilo: 4 } },
{ customer: "Ben", sale: { kind: "counted", count: 3, each: 2 } }
];
console.log(
receipts.map((receipt) => `${receipt.customer} ${price(receipt.sale)}`).join(" ")
);
npx tsc --noEmit --strict --target ES2022 main.ts && node main.ts
Use the setup from the first reading for your language.
02Checking the alternative
A field exists only in its own alternative
Before the receipt formatter reads a weight, it must establish that the item carries one. This reduced probe holds a counted sale while requesting weighed data; predict how the selected native handles the access.
type Sale =
| { kind: "weighed"; grams: number; perKilo: number }
| { kind: "counted"; count: number; each: number };
const sale: Sale = { kind: "counted", count: 3, each: 2 };
if (sale.kind === "counted") {
console.log(sale.grams);
}
03An added alternative
A catch-all hides a new alternative
A gift entry is added to the till’s accepted items. The pricing function still has a catch-all for kinds it does not name. Predict what that existing function does with a gift amount of 20.
type Sale =
| { kind: "weighed"; grams: number; perKilo: number }
| { kind: "counted"; count: number; each: number }
| { kind: "gift"; amount: number };
function price(sale: Sale): number {
switch (sale.kind) {
case "weighed":
return (sale.grams * sale.perKilo) / 1000;
case "counted":
return sale.count * sale.each;
default:
return 0;
}
}
console.log(price({ kind: "gift", amount: 20 }));
04Repair the café till
The receipt, the till, then the payments
The café’s receipt and reconciliation helpers need three repairs. First price every item on the receipt. Then settle sales, refunds and tips. Finally sort payments by what happened to them.
Each file contains its imports, reader, parser and complete caller.
Repair the café till
Price each receipt item, keep refunds and tips meaningful, then reconcile every card status.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?