TypeScript from zero: a union names the cases
A union is a value that is one of several shapes. Paid is yes with the cents, or no. Reading yes prints paid 450. Reading no prints unpaid.
Arthur is one of GoByte's characters. This post was drafted by AI agents in Arthur's voice, then fact checked, run and edited by the GoByte team.
A payment is sometimes an amount and sometimes the news that nobody has paid. A union writes both shapes. You tell them apart with a field, here kind, and the checker remembers which shape you are in.
The variant decides which fields exist#
A union is a value that has one of several shapes. Here the shapes share a kind field, and the rest of the fields depend on it. In the yes branch the checker narrows a so a.cents is a number. In the other branch a.cents does not exist, and reading it is an error. The narrowing is a compile-time fact. At runtime the if is an ordinary property check. Forgetting a variant is something the checker can see, as long as every variant carries the discriminant.
- yescentspaid 450
- nono centsunpaid
type Paid = { kind: "yes"; cents: number } | { kind: "no" };
function read(a: Paid): string {
if (a.kind === "yes") return "paid " + a.cents;
return "unpaid";
}
console.log(read({ kind: "yes", cents: 450 }));
console.log(read({ kind: "no" }));
paid 450
unpaid
kind picks the shape#
Paid is either an object with kind: "yes" and a number cents, or an object with kind: "no". read looks at kind. Inside the if, a.cents is allowed, because that arm is the yes shape. Outside it, a.cents does not compile. There is no amount on no.
{ kind: "yes" } without cents does not compile. { kind: "maybe" } does not compile. The set of cases is closed. A stringly "yes" returned from a looser function would not get this check. Keep the value as Paid until you turn it into text.
The other case is a return, not a crash#
read({ kind: "no" }) returns "unpaid". The function's return type is string either way, so the caller prints a string and does not test kind again. Handle the cases in the function that can see them. The next lesson uses an interface so a function can call one method and ignore the rest of the class.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.