03 narrowing
Narrowing is how TypeScript refines a broad type into a specific one using normal JavaScript control flow It is the feature that makes TypeScript feel like it reads your code
Table of Contents
typeof guards
function padLeft(padding: number | string, input: string): string {
if (typeof padding === "number") return " ".repeat(padding) + input;
return padding + input;
}
repeat needs a number
The guard proves padding is a number in that branch
After the return, TypeScript knows the remaining branch is string
typeof null is "object" in JavaScript
That is why the handbook example checks null explicitly before treating a value as an array
Truthiness
Values that coerce to false: 0 , NaN , "" , 0n , null , undefined
Everything else is truthy
function printAll(values: string | string[] | null): void {
if (values !== null && typeof values === "object") {
values.forEach((v) => console.log(v));
} else if (typeof values === "string") {
console.log(values);
}
}
A bare if (values) check silently drops the empty string
Use explicit null checks when empty string is a real value
Equality
=== , !== , == , and != all narrow
== null covers both null and undefined
That is sometimes exactly what you want
Discriminated unions
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; sideLength: number };
type Shape = Circle | Square;
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "square": return shape.sideLength ** 2;
default: {
const exhaustive: never = shape;
return exhaustive;
}
}
}
The kind field is the discriminant
Checking it removes union members that cannot match
No ! non-null assertion needed
Type predicates
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function isFish(pet: Fish | Bird): pet is Fish {
return "swim" in pet;
}
pet is Fish is a type predicate
After the check, the if branch is Fish and the else branch is Bird
never
never is the type of a state that should not exist
Assigning a value to never in the default branch gives exhaustiveness checking
Add a new member to Shape and the compiler points at the missing case
Posted