Sub topic 2
Narrowing with `switch` and `if`
Assume you know basic TypeScript types, object types, functions, and JavaScript control flow. A discriminated union is a union whose members share a property with different literal values. TypeScript uses that property to identify the current member.
Narrowing with `switch` and `if`
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
switch (shape.kind) {
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
}
}Inside the "circle" branch, TypeScript knows that shape has a radius. Inside the "square" branch, it knows that shape has a size. This process is called type narrowing.
Equality checks also narrow a union:
function label(shape: Shape): string {
return shape.kind === "circle"
? `Circle with radius ${shape.radius}`
: shape.kind === "square"
? `Square with size ${shape.size}`
: `Rectangle ${shape.width} × ${shape.height}`;
}Exhaustiveness checking with `never`
A later change might add a new shape and leave an existing function incomplete. Use never to make the compiler detect that omission.
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
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);
default:
return assertNever(shape);
}
}If Shape gains a "triangle" member, shape in the default branch is no longer never. TypeScript reports an error until you handle the triangle.
Modeling state so invalid states cannot exist
Unrelated optional properties can represent impossible combinations, such as loading and having an error simultaneously. A union gives each state its own valid fields.
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function describe<T>(state: RequestState<T>): string {
if (state.status === "success") {
return `Loaded ${JSON.stringify(state.data)}`;
}
if (state.status === "error") {
return `Failed: ${state.error.message}`;
}
return state.status;
}Exercise
What compiler error should appear after adding { kind: "triangle"; base: number; height: number } to Shape without updating perimeter?
Show answer
The assertNever(shape) call fails because shape may be a triangle, so it is not assignable to never.