×

typescript · level 3 · unit 6 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.