Type Guards
A type guard is a runtime check the compiler understands, so it can narrow a union or unknown inside a block. Built-in checks include typeof, instanceof, and in. You can also write your own predicate functions.
Detailed Explanation
Types are erased. The compiler cannot look at a value at runtime and see that it is a User. What it can do is follow JavaScript checks you already wrote and shrink the type on the true branch.
The built-in guards are the ones JavaScript already has:
typeof x === "string"(and"number","boolean","bigint","symbol","undefined","function","object")x instanceof Date(and any class)"email" in xfor object typesArray.isArray(x)- equality against a literal, including discriminants
- truthiness and nullish checks
Each of these has a hole. typeof null is "object". typeof cannot distinguish arrays from objects. in throws if the value is null or undefined. instanceof fails across realms (an array from an iframe is not instanceof Array). The compiler models the common cases, not every JavaScript quirk.
When the built-in checks are not enough, you write a user-defined type guard: a function whose return type is a type predicate.
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof (value as User).id === "string"
);
}
value is User is the predicate. After if (isUser(x)), x has type User. The compiler does not verify that the function body is a complete check. It trusts the predicate. A sloppy guard is a soundness hole you wrote yourself.
An assertion function is the throwing cousin: function assertUser(value: unknown): asserts value is User. After a call, the value is User in the rest of the scope, or the function threw. Same trust issue.
Guards are how you make unknown usable, how you narrow a union that has no discriminant, and how you validate data at a boundary. For anything that came from JSON, a network, or a database, a hand-rolled guard is easy to get wrong. A schema library that produces a type from a runtime schema (Zod, Valibot, ArkType) keeps the check and the type in one place.
Do not use a type assertion (as User) where a guard belongs. An assertion changes the type and runs nothing. A guard runs code. That is the difference that matters when the payload is wrong.
Code Examples
1. Built-in guards on a union.
// 1. Built-in guards on a union.
function describe(id: string | number | Date): string {
if (typeof id === "string") return id.toUpperCase();
if (typeof id === "number") return id.toFixed(0);
if (id instanceof Date) return id.toISOString();
return id;
}2. A user-defined predicate for unknown input.
// 2. A user-defined predicate for unknown input.
type User = { id: string; email: string };
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) return false;
const rec = value as Record<string, unknown>;
return typeof rec.id === "string" && typeof rec.email === "string";
}
function emailOf(raw: unknown): string | undefined {
if (!isUser(raw)) return undefined;
return raw.email;
}3. An assertion function that narrows the rest of the scope.
// 3. An assertion function that narrows the rest of the scope.
function assertUser(value: unknown): asserts value is User {
if (!isUser(value)) {
throw new Error("expected User");
}
}
function mustEmail(raw: unknown): string {
assertUser(raw);
return raw.email;
}Common Gotchas
The compiler does not check the body of a predicate
`function isUser(v: unknown): v is User { return true; }` compiles and then lies at every call site. Test the guard with values that should fail.
`typeof null === "object"`
a guard that checks `typeof value === "object"` must also reject `null` before reading properties.
Predicates do not survive a function boundary unless you call them again
passing a narrowed value into a nested function resets the type to the parameter's declared type.
`instanceof` is realm-sensitive
values from another iframe or Node `vm` context can fail `instanceof` even when they have the right shape. Prefer a predicate that checks members for those boundaries.