Lesson 21 / 26
Discriminated Unions
A shared literal field lets TS narrow a union exhaustively.
A discriminated union
Give every variant a shared literal field (kind) — TS uses it to know exactly which shape you're holding.
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
side: number;
}
type Shape = Circle | Square;Exhaustive switch
Switching on kind narrows each case automatically, with no manual casting.
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
}
}Exhaustiveness checking
Add a default: const _exhaustive: never = shape; branch — if a new shape variant is ever added and not handled, TS flags it at compile time.