Sub topic 3
How TypeScript Narrows Types
Assume you know basic TypeScript types, object types, functions, if statements, and switch statements. Also assume that strict: true is enabled in tsconfig.json.
A union type says that a value can have one of several types:
type Input = string | number;
function format(input: Input): string {
if (typeof input === "string") {
return input.toUpperCase();
}
return input.toFixed(2);
}Inside the if block, TypeScript narrows input from string | number to string. After the block, the remaining possibility is number. Narrowing is TypeScript's process for removing impossible members from a union based on information in your code.
Narrowing with a discriminant
A discriminated union gives every member a shared property with a different literal value. That property is the discriminant, or tag.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };The type of kind is not just string. Each member has a specific literal type: "circle", "square", or "rectangle".
When you compare the discriminant, TypeScript selects the matching member:
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;
}
console.log(area({ kind: "circle", radius: 3 }));
console.log(area({ kind: "rectangle", width: 4, height: 5 }));In the first block, shape is known to be the circle member, so shape.radius is available. In the second block, it is known to be the square member. Once those cases are excluded, the final branch contains the rectangle member.
Using `switch`
A switch statement often makes variant handling easier to read:
function describe(shape: Shape): string {
switch (shape.kind) {
case "circle":
return `Circle with radius ${shape.radius}`;
case "square":
return `Square with side ${shape.size}`;
case "rectangle":
return `Rectangle ${shape.width} by ${shape.height}`;
}
}Each case narrows shape to the member whose kind matches the case value. TypeScript performs this analysis through control flow. It follows the conditions that can be true at each point in the function.
Equality checks and aliases
Equality checks also narrow values. If two variables share a union, comparing them can reveal a common literal type:
type Status = "idle" | "ready" | "failed";
function isReady(status: Status, expected: "ready" | "failed"): boolean {
if (status === expected) {
return status === "ready";
}
return false;
}You can store a discriminant in a const and use it in a condition, but keep related values together when possible. TypeScript's analysis is strongest when the check and the property access stay in the same control-flow branch.
A common mistake
Checking a property that is not shared consistently across members can prevent useful narrowing. Optional properties are especially risky because a missing property and an explicitly assigned value may both be possible. A required literal discriminant gives each variant a clear identity.
Exercise
In the Shape union, what type does TypeScript assign to shape inside the branch if (shape.kind === "rectangle")?
Show answer
It narrows shape to { kind: "rectangle"; width: number; height: number }, so width and height are available.