Narrowing on the Discriminant
Let TypeScript narrow variants in switch statements.
Narrowing on the Discriminant
Once you check the discriminant, TypeScript narrows the union to the matching member and unlocks its specific fields. This is the payoff of the pattern.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function area(s: Shape) {
if (s.kind === "circle") return Math.PI * s.radius ** 2;
return s.side ** 2;
}
console.log(area({ kind: "circle", radius: 2 }).toFixed(2));Switch on the Discriminant
A switch over the discriminant is the cleanest way to handle every variant. Inside each case, the type is narrowed automatically.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "square": return s.side ** 2;
}
}
console.log(area({ kind: "square", side: 5 }));All lessons in this course
- Building Discriminated Unions
- Narrowing on the Discriminant
- Exhaustiveness Checking with never
- Modeling State Machines