TypeScript · Narrowing and unions
Discriminated union
A shared literal field lets TypeScript narrow the whole object in a switch.
Syntax
type Shape = { kind: "circle"; r: number } | …Example
Example
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; size: number };
function area(shape: Shape) {
return shape.kind === "circle" ? Math.PI * shape.r ** 2 : shape.size ** 2;
}More in this group
Learn this in the course
Reference pages are the quick answer. The course explains the why, shows the full example and ends with a challenge.