AI Hints
Home›TypeScript Tutorial›Literal and Discriminated Unions
TypeScript · Lesson 35 of 120

Discriminated Unions

A kind field.

⏱ 2 min read▶ Video at 27:40🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

A discriminated union is a union of object shapes, each with a shared field holding a different literal. Often called kind. Checking that field tells TypeScript exactly which shape you have.

Discriminated Unions
From the video: Discriminated Unions
  • Several shapes
  • A kind field
  • Check it

Payment methods

Each payment shape has a kind. Card has the last four digits. PayPal has an email. Voucher has a code. A switch on kind narrows each case. Run it.

app.tstypescript
type Payment =
  | { kind: "card"; last4: string }
  | { kind: "paypal"; email: string }
  | { kind: "voucher"; code: string };

function describe(p: Payment): string {
  switch (p.kind) {
    case "card": return `Card ending ${p.last4}`;
    case "paypal": return `PayPal (${p.email})`;
    case "voucher": return `Voucher ${p.code}`;
  }
}

console.log(describe({ kind: "card", last4: "4242" }));
console.log(describe({ kind: "voucher", code: "BIKE20" }));
Output
Card ending 4242
Voucher BIKE20

Summary

A shared kind field lets a switch narrow each case of a union. Next, exhaustive checks.

Key takeaways
  • kind: 'card'
  • switch (p.kind)
  • Each case narrowed
Next up: Exhaustive Checks — never miss a case