Lesson 5 of 10
Discriminated unions
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
An impossible state can't be written
Explanation
A single object with an optional field for every possibility, like { kind: string; radius?: number; width?: number }, looks flexible. But it accepts a circle with no radius and makes you write ! every time you read a field, and ! is just a promise you make to the compiler that nobody checks.
A discriminated union describes each case on its own and gives every case a shared field with a fixed value, like this: { kind: "circle"; radius: number } | { kind: "rect"; width: number; height: number }. Checking kind is all it takes for the compiler to know which branch you're in.
Inside case "circle":, shape.radius is a guaranteed number, and shape.width is a type error, because a circle really has no width.
Your task
Redefine Shape as a union of { kind: "circle"; radius: number } and { kind: "rect"; width: number; height: number }, then write area with a switch on shape.kind and no ! at all.
Checks
5 checks- No type errors
- The circle's area is correct
- The rectangle's area is correct
- The compiler knows the fields of each branch
- A circle without a radius is rejected