TypeScript Narrowing & Type Guards
When a value has a union type such as string | number, TypeScript only lets you use the operations that are valid for every member of the union. To do something specific — call .toUpperCase() on the string, or .toFixed() on the number — you first have to prove which member you have. That process is called narrowing, and the checks that do it are called type guards.
The nice thing is that you don't need special syntax: TypeScript understands ordinary JavaScript checks like typeof, instanceof, in and ===, and it follows your if/else branches, return statements and switch cases to work out the type at each point of the code. This is called control-flow analysis.
Why narrowing is needed
Here is a function that tries to use a string method on a union without checking first. The type checker refuses:
function shout(value: string | number) {
return value.toUpperCase();
}
console.log(shout("hi"));main.ts(2,16): error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
Property 'toUpperCase' does not exist on type 'number'.
The fix is a typeof check. Inside the if, value is string; after the early return, TypeScript knows only number is left:
function shout(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase(); // value: string
}
return value.toFixed(1) + "!"; // value: number
}
console.log(shout("hi"));
console.log(shout(7));HI
7.0!
The built-in type guards
| Guard | Narrows | Example |
|---|---|---|
typeof x === "string" |
primitives (string, number, boolean, bigint, symbol, undefined, function, object) |
typeof id === "number" |
x instanceof C |
class instances | err instanceof RangeError |
"key" in x |
object types that declare that property | "swim" in pet |
x === value / x !== null |
literal and nullable types | if (user !== undefined) |
truthiness if (x) |
removes null, undefined, "", 0, false |
if (title) |
Array.isArray(x) |
arrays | Array.isArray(input) |
class Circle { constructor(public radius: number) {} }
class Square { constructor(public side: number) {} }
type Bird = { fly(): string };
type Fish = { swim(): string };
function area(shape: Circle | Square): number {
if (shape instanceof Circle) {
return Math.round(Math.PI * shape.radius ** 2);
}
return shape.side * shape.side;
}
function move(pet: Bird | Fish): string {
return "fly" in pet ? pet.fly() : pet.swim();
}
function total(input: number | number[]): number {
return Array.isArray(input) ? input.reduce((a, b) => a + b, 0) : input;
}
console.log(area(new Circle(2)), area(new Square(3)));
console.log(move({ swim: () => "splash" }));
console.log(total([1, 2, 3]), total(10));13 9
splash
6 10
Note:
typeof nullis"object"in JavaScript. If a value can beobject | null, atypeof x === "object"check alone does not removenull— combine it withx !== null.
Truthiness and equality narrowing
Checking a value in an if removes the "falsy" members. Comparing two values with === narrows both to their common type:
function greet(nickname?: string): string {
if (nickname) {
return `Hey, ${nickname}!`; // nickname: string
}
return "Hello, stranger."; // nickname: string | undefined
}
function same(a: string | number, b: string | boolean): string {
if (a === b) {
return a.toUpperCase(); // both must be string here
}
return "different";
}
console.log(greet("Linh"));
console.log(greet());
console.log(same("ok", "ok"), same(1, true));Hey, Linh!
Hello, stranger.
OK different
Tip: Be careful with truthiness on numbers and strings:
0and""are falsy, soif (count)would treat a count of zero as "missing". Usecount !== undefinedwhen zero is a valid value.
User-defined type guards
Sometimes the check is too complex for the built-in guards — for example validating the shape of unknown data. You can write your own guard: a function whose return type is a type predicate param is Type. When it returns true, TypeScript narrows the argument.
interface Product {
title: string;
price: number;
}
function isProduct(value: unknown): value is Product {
return (
typeof value === "object" &&
value !== null &&
typeof (value as Product).title === "string" &&
typeof (value as Product).price === "number"
);
}
const raw: unknown[] = [
{ title: "Pen", price: 2 },
{ title: "Broken" },
"not even an object",
{ title: "Mug", price: 8 },
];
const products = raw.filter(isProduct); // Product[]
for (const p of products) {
console.log(`${p.title}: ${p.price}`);
}Pen: $2
Mug: $8
Since TypeScript 5.5, simple arrow functions such as x => x !== undefined are inferred as type predicates automatically, so [1, undefined, 3].filter(x => x !== undefined) already has the type number[].
Assertion functions
An assertion function throws when a condition fails, and its asserts return type tells TypeScript that after the call the condition holds:
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new Error(`Expected a string, got ${typeof value}`);
}
}
function lengthOf(value: unknown): number {
assertIsString(value);
return value.length; // value: string from here on
}
console.log(lengthOf("typescript"));
try {
lengthOf(42);
} catch (err) {
console.log((err as Error).message);
}10
Expected a string, got number
Test yourself
Inside if (typeof v === "number") { ... } where v: string | number, what is the type of v?
- string | number
- number
- string
- unknown
What is the return type annotation of a user-defined type guard for Fish?
booleanFishpet is Fishasserts Fish
Why can typeof x === "object" fail to fully narrow object | null?
typeofdoesn't work on objectstypeof nullis also "object"- TypeScript ignores
typeoffor objects - It only works with classes