Sub topic 6
Narrowing with `switch` and `if`
Assume you know basic TypeScript types, object types, functions, and JavaScript if and switch statements. Also assume strict: true is enabled in tsconfig.json.
A discriminated union is useful because TypeScript can narrow it after checking a shared property. Narrowing means reducing a broad type to one more specific type inside a section of code.
Consider this union:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };Every member has a kind property, but each member gives it a different string literal type. The kind property is the discriminant. When TypeScript knows that kind is "circle", it also knows that the value has a radius property.
Narrowing with `if`
An equality check on the discriminant narrows the value:
function describe(shape: Shape): string {
if (shape.kind === "circle") {
return `Circle with radius ${shape.radius}`;
}
if (shape.kind === "square") {
return `Square with side ${shape.size}`;
}
return `Rectangle ${shape.width} by ${shape.height}`;
}Inside the first block, shape has the type { kind: "circle"; radius: number }. Accessing shape.size there would be a compile-time error because circles do not have a size property.
The final return works because the earlier checks removed the circle and square members from the possible types. Only the rectangle member remains.
You can also use an early return to keep the remaining code simple:
function area(shape: Shape): number {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
if (shape.kind === "square") {
return shape.size ** 2;
}
return shape.width * shape.height;
}Narrowing with `switch`
A switch often makes a discriminated union easier to read when there are several variants:
function perimeter(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 2 * Math.PI * shape.radius;
case "square":
return 4 * shape.size;
case "rectangle":
return 2 * (shape.width + shape.height);
}
}Each case narrows shape to the matching union member. The compiler therefore permits only the properties belonging to that member.
A switch compares the discriminant with literal values. This is more precise than checking whether a property merely exists. For example, checking "radius" in shape can work, but it couples the logic to property names instead of the union’s intended tag.
Equality checks and variables
You can store the tag in a variable and compare it, but preserve the connection between the tag and the object:
function label(shape: Shape): string {
const kind = shape.kind;
if (kind === "circle") {
return `Circle: ${shape.radius}`;
}
if (kind === "square") {
return `Square: ${shape.size}`;
}
return `Rectangle: ${shape.width} × ${shape.height}`;
}Checking an unrelated string does not narrow the object:
function broken(shape: Shape, kind: string): number {
if (kind === "circle") {
// shape is still Shape here.
return shape.radius;
}
return 0;
}The compiler cannot know that the separate kind parameter came from shape.
The narrowing flow
When you add a new union member, revisit every if chain and switch. An exhaustive check with never can make forgotten cases compiler errors, especially in larger programs.
Exercise
Inside if (shape.kind === "square"), which properties can TypeScript safely allow on shape?
Show answer
It narrows shape to the square member, so kind and size are available, but radius, width, and height are not.