Type narrowing
Overview
A union says “it could be any of these”. Before you can use member-specific features, you have to find out which one you have. Narrowing is how: you write an ordinary JavaScript check, and TypeScript understands it and refines the type for the code that follows. No casts, no special syntax — just the checks you’d write anyway.
Control flow analysis
TypeScript reads your code the way you do. After a check, it knows which types are still possible on each path — inside the if, after an early return, in each case of a switch. This is called control flow analysis, and every technique below plugs into it.
typeof
For primitives, typeof is the tool:
function pad(value: string | number) {
if (typeof value === "number") {
return " ".repeat(value); // value: number
}
return value; // value: string
}TypeScript understands the results "string", "number", "bigint", "boolean", "symbol", "undefined", "object" and "function". Beware one JavaScript quirk: typeof null is "object", so a typeof x === "object" check doesn’t rule out null — TypeScript knows that and keeps null in the type.
Truthiness
if (value) removes null, undefined and the other falsy values:
function greet(name: string | undefined) {
if (name) {
return `Hello, ${name}`; // name: string
}
return "Hello, stranger";
}Careful: for strings and numbers, "" and 0 are falsy too. If they’re valid values, compare explicitly (name !== undefined).
Equality
Comparing with ===, !==, == or != narrows both sides:
function check(a: string | number, b: string | boolean) {
if (a === b) {
// the only type both can share: a: string, b: string
}
}
function len(text: string | null | undefined) {
if (text == null) return 0; // == null matches both null and undefined
return text.length; // text: string
}Comparing against literal values narrows literal unions: after if (size === "sm") return …, size is "md" | "lg".
instanceof
For values created from classes — Date, Error, Map, your own classes:
function toTime(value: Date | string): number {
if (value instanceof Date) return value.getTime(); // value: Date
return Date.parse(value); // value: string
}Array.isArray
function toList(input: string | string[]): string[] {
return Array.isArray(input) ? input : [input];
}The in operator
For unions of object types, check for a property that only some members have:
type Cat = { name: string; meow(): string };
type Dog = { name: string; bark(): string };
function speak(pet: Cat | Dog) {
if ("meow" in pet) return pet.meow(); // pet: Cat
return pet.bark(); // pet: Dog
}in also narrows unknown values, as you saw in any, unknown and never: if (typeof data === "object" && data !== null && "port" in data) makes data.port readable.
Assignment
Assigning to a variable narrows it to the type of what you assigned:
let value: string | number = Math.random() > 0.5 ? "a" : 1;
value = "hello";
value.toUpperCase(); // value: string — TypeScript saw the assignmentswitch
switch narrows in each case, exactly like a chain of === checks:
function label(size: "sm" | "md" | "lg") {
switch (size) {
case "sm": return "Small";
case "md": return "Medium";
case "lg": return "Large";
}
}Because every case returns, TypeScript knows the function always returns a string. Combined with object unions, switch becomes the main tool of the next lesson.
When nothing is left: never
Each check removes possibilities. When all have been removed, what remains is never:
function format(value: string | number) {
if (typeof value === "string") return value;
if (typeof value === "number") return String(value);
const impossible: never = value; // ✓ nothing left
}If someone later adds boolean to the union, that last line fails to compile — pointing straight at the function that needs updating. Discriminated unions uses this trick for exhaustive switch statements.
Where narrowing gets lost
Narrowing applies to a specific variable or property path in a specific place. It resets when TypeScript can’t be sure the value is unchanged:
- inside callbacks that run later (copy into a
constfirst); - after a function call that might modify the object — though TypeScript is optimistic here and usually keeps property narrowing;
- for different expressions: checking
data.items[0]doesn’t narrowdata.items[i].
When narrowing doesn’t stick, assign the value to a const, narrow that, and use it.
Writing your own checks
When the built-in checks aren’t enough — say, to check that an unknown value has the shape of a User — you can write a function that narrows. That’s a type guard, covered in Custom type guards.
Remember: write the check you’d write in JavaScript, and TypeScript will follow it. Prefer early returns, use the technique that matches the kind of type, and let
nevertell you when you’ve covered everything.
Describe anything
Write describe(value: string | number | boolean | Date | string[] | null | undefined): string using a different narrowing technique for each case: null/undefined → "empty" (equality with == null); a string → text "…" with its length (typeof); a number → number 3.14 with 2 decimals, or "not a number" for NaN (typeof + Number.isNaN); a boolean → yes/no; a Date → date 2026-12-04 (instanceof); an array → list of 3: a, b, c (Array.isArray). Then write speak(pet: Cat | Dog): string using the in operator. Print a line for each test value in the starter.
type Cat = { name: string; meow(): string };
type Dog = { name: string; bark(): string };
// describe()
// speak()
const values = ["hello", 3.14159, Number.NaN, true, new Date("2026-12-04T00:00:00Z"), ["a", "b", "c"], null, undefined];type Cat = { name: string; meow(): string };
type Dog = { name: string; bark(): string };
function describe(value: string | number | boolean | Date | string[] | null | undefined): string {
if (value == null) return "empty"; // null and undefined
if (typeof value === "string") return `text "${value}" (${value.length})`;
if (typeof value === "number") {
return Number.isNaN(value) ? "not a number" : `number ${value.toFixed(2)}`;
}
if (typeof value === "boolean") return value ? "yes" : "no";
if (value instanceof Date) return `date ${value.toISOString().slice(0, 10)}`;
return `list of ${value.length}: ${value.join(", ")}`; // only string[] is left
}
function speak(pet: Cat | Dog): string {
if ("meow" in pet) return `${pet.name}: ${pet.meow()}`;
return `${pet.name}: ${pet.bark()}`;
}
const values = ["hello", 3.14159, Number.NaN, true, new Date("2026-12-04T00:00:00Z"), ["a", "b", "c"], null, undefined];
for (const v of values) console.log(describe(v));
console.log(speak({ name: "Tom", meow: () => "Meow" }));
console.log(speak({ name: "Rex", bark: () => "Woof" }));Summary
- Narrowing turns a broad type into a specific one inside a branch; TypeScript tracks it through ifs, returns, switches and loops.
typeofnarrows primitives;instanceofnarrows class instances;Array.isArraynarrows arrays.innarrows object unions by checking for a property;===,!==and== nullnarrow by value.- After all members have been handled, the remaining type is
never— useful for exhaustiveness checks. - Early returns narrow everything below them, keeping code flat and readable.