Discriminated unions
Real data often comes in a few different shapes. A payment might be cash, card or mobile money, and each needs different fields. A discriminated union models this with a shared literal property (the discriminant) that says which shape you have:
type Payment =
| { method: "cash" }
| { method: "card"; last4: string }
| { method: "mobile"; phone: string; network: "EcoCash" | "OneMoney" };
Checking the discriminant narrows to the right shape, so TypeScript knows which fields exist:
function describe(p: Payment): string {
switch (p.method) {
case "cash":
return "Cash";
case "card":
return `Card ending ${p.last4}`; // p is the card shape here
case "mobile":
return `${p.network} ${p.phone}`; // and the mobile shape here
}
}
Proving every case is handled
The type never means "this cannot happen". After every case is handled, the value in the default branch has type never. If someone later adds a new shape and forgets to handle it, the value is no longer never and the assignment becomes a type error, pointing straight at the place to fix:
default: {
const unreachable: never = p;
throw new Error(`Unknown payment: ${JSON.stringify(unreachable)}`);
}
This turns "I hope I updated every switch" into a compiler guarantee.
Your task
- Add a triangle to
Shape:{ kind: "triangle"; base: number; height: number }. - Make
areahandle it (base times height divided by 2), keeping thenevercheck so there are no type errors.