Skip to content
dreamcode
dreamcode
Map
Tagged unions
Lesson 9 of 26
+15 XP on finish
TS UNIONSChapter 2 · TS Unions & Enums

Discriminated Unions

A discriminated union is a union of object types that share one literal property, the tag, such as kind: "circle" or kind: "square". Checking the tag narrows to exactly one member, so each branch knows which properties exist. Add a never check in the default branch and TypeScript will flag any member you forget to handle.

Worked example

How it reads

  • kind is the tag every member shares
  • Inside case "circle", only radius is available
  • Assigning to never fails to compile if a case was missed
Cloud tip: Tagged unions are the TypeScript way to model states: loading, success, error. Each state carries only the data that makes sense for it.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Handle the "land" case so it returns Nova landed on Moon for the event in the starter.

Press Run to check your work.