Sub topic 6
Narrowing with switch and if
What you need before this chapter
This chapter assumes you can read basic TypeScript types, you know how if and switch work, and your tsconfig.json has "strict": true. It also assumes you have seen a discriminated union defined, which is a union of object types that each carry a literal-typed tag property. Here you will see how the compiler uses that tag inside conditionals.
A check on the tag narrows the whole object
A union value could be any member, so you can only touch the properties that every member shares. The tag is shared, so you can always read it. Once you compare the tag against a literal, TypeScript removes every member that cannot match. This is called narrowing. The comparison is the only thing you write. No cast is involved.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function describe(shape: Shape): string {
// Here shape is the full union, so only shape.kind is readable.
if (shape.kind === "circle") {
// Here shape is { kind: "circle"; radius: number }.
return `circle with radius ${shape.radius}`;
}
// Here the circle member has been removed from the union.
return `polygon of kind ${shape.kind}`;
}
console.log(describe({ kind: "circle", radius: 2 }));
console.log(describe({ kind: "square", size: 3 }));After the if returns, TypeScript knows the circle case is gone. In the last line, shape is the square-or-rectangle union, and shape.kind has the type "square" | "rectangle".
Narrowing with switch
A switch on the tag is the usual choice when you handle every member. Each case label is a literal comparison, so the type inside that case is the matching member.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
}
}
console.log(area({ kind: "rectangle", width: 2, height: 5 }));Under strict, this function compiles without a final return. TypeScript sees that every member is handled, so the end of the function cannot be reached. If you add a fourth member to Shape, the function stops compiling with "Function lacks ending return statement and return type does not include undefined". That error is a basic form of exhaustiveness checking. The next chapter makes the check explicit with never.
Grouping cases
Stacked case labels narrow to the union of the listed members. Inside the group you can read only the properties that those members share.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function hasStraightEdges(shape: Shape): boolean {
switch (shape.kind) {
case "square":
case "rectangle":
// shape is square | rectangle here, but not circle.
return true;
case "circle":
return false;
}
}
console.log(hasStraightEdges({ kind: "square", size: 1 }));Fallthrough and default
Narrowing follows control flow. If a case has no break or return, execution falls into the next case, and the type there is the union of both paths. Avoid this where you can. Under noFallthroughCasesInSwitch, the compiler reports non-empty cases that fall through, which catches the mistake early.
A default branch receives every member not named in an earlier case. That is useful for a fallback, but it hides new members. A default that returns a neutral value will quietly swallow a variant you add later. Prefer naming every case, and use default only for a deliberate catch-all.
Narrowing with if and early returns
Use if when you care about one or two members. The guard-clause style keeps the main path flat. Each early return removes a member from what follows.
type Event =
| { type: "click"; x: number; y: number }
| { type: "keypress"; key: string }
| { type: "scroll"; delta: number };
function summarize(event: Event): string {
if (event.type === "click") {
return `click at ${event.x},${event.y}`;
}
if (event.type === "keypress") {
return `key ${event.key}`;
}
// Only the scroll member is left.
return `scroll by ${event.delta}`;
}
console.log(summarize({ type: "scroll", delta: -40 }));Equality operators that narrow
All of these narrow on a literal tag:
===and!==narrow in the true and false branches respectively.==and!=also narrow, but they invite coercion habits, so stay with the strict forms.- A
switchuses strict equality for each case. - Ternaries and
&&narrow within their right-hand side, as inshape.kind === "circle" && shape.radius.
With a boolean tag, the tag itself is the condition. For { ok: true; value: T } | { ok: false; error: E }, writing if (result.ok) narrows to the first member, and the else branch holds the second. This only works when the tag type is exactly true and false. If it is plain boolean, nothing is narrowed.
The in operator
The in operator also narrows. It is useful when a union has no tag, for example two types from a library you do not control.
type Cat = { meow: () => string };
type Dog = { bark: () => string };
function speak(pet: Cat | Dog): string {
if ("meow" in pet) {
return pet.meow();
}
return pet.bark();
}
console.log(speak({ bark: () => "woof" }));This works only while each property name appears in just some members. If you control the types, add a tag and compare it instead. A tag states your intent and keeps working when you add properties later.
Destructuring a tagged union
Since TypeScript 4.6, destructuring the tag together with other fields narrows them as a group. This requires a const declaration, and the destructured properties must come from a discriminated union.
type Action =
| { kind: "add"; payload: number }
| { kind: "label"; payload: string };
function apply(action: Action): string {
const { kind, payload } = action;
if (kind === "add") {
return `adding ${payload.toFixed(1)}`; // payload is number
}
return `labelling ${payload.toUpperCase()}`; // payload is string
}
console.log(apply({ kind: "add", payload: 3 }));Destructuring into separate steps does not give you this. If you write const { kind } = action and later read action.payload, action is still the full union.
Where narrowing stops working
Narrowing is a property of one variable or property path at one point in the control flow. It does not carry through everything.
- Callbacks. A callback can run later, so TypeScript resets narrowing for mutable
letvariables and for properties inside it. Aconstor areadonlyparameter keeps its narrowed type. When you need a narrowed value in a callback, copy it to aconstfirst. - Array methods.
shapes.filter(s => s.kind === "circle")returnsShape[]in versions before TypeScript 5.5. Write the predicate yourself:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
const shapes: Shape[] = [
{ kind: "circle", radius: 1 },
{ kind: "square", size: 2 },
];
const circles = shapes.filter(
(s): s is Extract<Shape, { kind: "circle" }> => s.kind === "circle",
);
console.log(circles.map((c) => c.radius));- Wide tags. If the tag has type
stringinstead of a literal, comparing it narrows nothing. This happens with object literals assigned to a plainconst, and a later chapter covers it. - Reassignment. Assigning to the variable inside the branch discards the narrowing. The type becomes whatever you assigned.
Choosing between switch and if
| Situation | Better fit | Reason |
|---|---|---|
| Handle every member | `switch` | The compiler can verify the cases are complete |
| Handle one member, ignore the rest | `if` | Less code, and the other members need no branch |
| Reject bad members early | `if` with return | The main path stays flat |
| Two members share handling | `switch` with stacked cases | The group narrows to a union |
| Boolean tag such as `ok` | `if (result.ok)` | The condition is the tag |
Exercise
Given type Event = { type: "click"; x: number } | { type: "key"; key: string } | { type: "tick" }, write a function label(event: Event): string that returns "click:<x>" for clicks, "key:<key>" for key events, and "tick" for ticks, using a switch so that TypeScript accepts the function with no final return statement.
Show answer
function label(event: Event): string { switch (event.type) { case "click": return click:${event.x}; case "key": return key:${event.key}; case "tick": return "tick"; } } Because every member of the union has a case that returns, the end of the function is unreachable under strict mode, so no extra return is needed. Adding a new member to Event makes this function fail to compile.
Exercise
A function receives result: { ok: true; value: number } | { ok: false; error: string }. In the code if (!result.ok) { return result.error; } return result.value;, what is the type of result on the last line, and why?
Show answer
It is { ok: true; value: number }. The condition !result.ok is true only for the member whose ok tag is false, and that branch returns. After it, the false member has been removed from the union, so result.value is available as a number.