1. Concept library
  2. JavaScript & TypeScript
  3. Module 4: Narrowing and control flow

Concept

Discriminated unions

Give every member of a union a shared literal property, such as kind, and a switch on it narrows to the exact member. It is the standard way to model states, events and results.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a discriminant property is and why every variant needs one
  2. Model the states of a request as a discriminated union
  3. Write a switch on the discriminant that narrows to each variant

In practice

A few lines that show Discriminated unions doing its job.

TypeScript
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rect"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.radius ** 2;
    case "rect":   return shape.width * shape.height;
  }
}

The common mistake

Watch for

Using an optional property per variant instead of a discriminant, like { radius?: number; width?: number }. Nothing then stops a value having both or neither, and every access needs a null check.

What to know first

Your roadmap puts these before Discriminated unions, unless you already know them.

How it stays learned

Once a session shows you understand Discriminated unions, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Discriminated unions.

Previous in the module← typeof and in guards
Next in the moduleExhaustiveness checks →