Lesson 5 of 10

Discriminated unions

Goal

An impossible state can't be written

01

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.

02

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
  1. No type errors
  2. The circle's area is correct
  3. The rectangle's area is correct
  4. The compiler knows the fields of each branch
  5. A circle without a radius is rejected
03

Hints

0/3
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.