Concept
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.
The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.
A few lines that show Discriminated unions doing its job.
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;
}
}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.
Your roadmap puts these before Discriminated unions, unless you already know them.
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.
Topics that build on Discriminated unions.