Custom type guards
Overview
The built-in checks — typeof, instanceof, in — cover a lot, but not everything. What if you need a reusable check like “is this a valid Product?” A normal function returning boolean doesn’t help: TypeScript can’t see inside it. Type guards are functions whose return type tells TypeScript what a true result proves.
The problem
function isCat(pet: Cat | Dog): boolean {
return "meow" in pet;
}
if (isCat(pet)) {
pet.meow();
// error TS2339: Property 'meow' does not exist on type 'Cat | Dog'.
// Property 'meow' does not exist on type 'Dog'.
}From the outside, isCat just returns a boolean. TypeScript doesn’t know what true means.
Type predicates: value is Type
Change the return type to a type predicate:
function isCat(pet: Cat | Dog): pet is Cat {
return "meow" in pet;
}
if (isCat(pet)) {
pet.meow(); // pet: Cat
} else {
pet.bark(); // pet: Dog
}pet is Cat means: this function returns a boolean, and if it’s true, the argument is a Cat. In the else branch, TypeScript removes Cat from the union.
Guards for unknown data
Type guards are especially useful for checking unknown values, such as parsed JSON:
type User = { id: number; name: string };
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value && typeof value.id === "number" &&
"name" in value && typeof value.name === "string"
);
}
const data: unknown = JSON.parse(text);
if (isUser(data)) {
console.log(data.name.toUpperCase()); // data: User
}Each && narrows a little further — after "id" in value, TypeScript lets you read value.id — so the function body type-checks without casts.
Filtering arrays
Pass a type guard to filter, and the result has the narrower type:
const valid = items.filter(isUser); // User[]Since TypeScript 5.5, simple predicates are inferred automatically — you don’t even need to write the guard:
const names = ["asha", undefined, "ben"];
const defined = names.filter((n) => n !== undefined); // string[]TypeScript infers n is string from the arrow function’s body. This works for straightforward checks (!== undefined, !== null, typeof x === "string"); for anything more involved, write the predicate yourself.
Assertion functions: asserts value is Type
Sometimes you don’t want an if — you want to stop with an error if the check fails, and carry on with the narrowed type if it passes. That’s an assertion function:
function assertIsUser(value: unknown): asserts value is User {
if (!isUser(value)) {
throw new Error("Expected a user");
}
}
const data: unknown = JSON.parse(text);
assertIsUser(data);
console.log(data.name); // data: User from here onThe return type asserts value is User tells TypeScript: if this function returns at all, value is a User. There’s also a plain form for conditions:
function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
}
assert(user !== undefined, "user must be loaded");
user.name; // narrowedOne rule: assertion functions must be called through a name with an explicit type — a function declaration (as above) or a const with an annotated function type. Inline arrow functions without an annotation can’t be used as assertions.
TypeScript trusts you
A type guard is a promise. TypeScript checks that the function returns a boolean, but not that the logic actually proves the predicate:
function isUser(value: unknown): value is User {
return true; // compiles fine — and lies
}A wrong guard is as dangerous as a wrong as cast. Keep guards small, check every property you rely on, and test them with good and bad inputs (Testing with Vitest).
Guards vs schema libraries
Hand-written guards are fine for a few small types. For bigger, nested data, writing and maintaining them gets tedious and error-prone. Schema libraries such as Zod let you describe the shape once and give you both the run-time check and the TypeScript type:
const User = z.object({ id: z.number(), name: z.string() });
type User = z.infer<typeof User>;
if (User.safeParse(data).success) { … }That’s the subject of Validating external data.
Remember:
value is Tfor checks used inifandfilter;asserts value is Tfor “check or throw”; and test your guards, because TypeScript believes them.
Guard incoming data
Parsed JSON is unknown. Write a type guard isProduct(value: unknown): value is Product that checks value is a non-null object with a string name, a finite number price ≥ 0, and a tags array whose items are all strings. Use it to keep only valid products from the incoming array (with filter) and print their names. Then write an assertion function assertProduct(value: unknown): asserts value is Product that throws Error("invalid product") when the guard fails; use it on two values, catching the error. Finally show (with // @ts-expect-error) that you can’t read .price on an unknown without a guard.
type Product = { name: string; price: number; tags: string[] };
const incoming: unknown[] = JSON.parse(`[
{ "name": "Lamp", "price": 24.99, "tags": ["home"] },
{ "name": "Ghost", "price": -1, "tags": [] },
{ "name": "Pen", "price": 1.25, "tags": ["office", 7] },
null,
{ "name": "Mug", "price": 8, "tags": [] }
]`);
// isProduct()
// keep the valid ones
// assertProduct()type Product = { name: string; price: number; tags: string[] };
const incoming: unknown[] = JSON.parse(`[
{ "name": "Lamp", "price": 24.99, "tags": ["home"] },
{ "name": "Ghost", "price": -1, "tags": [] },
{ "name": "Pen", "price": 1.25, "tags": ["office", 7] },
null,
{ "name": "Mug", "price": 8, "tags": [] }
]`);
function isProduct(value: unknown): value is Product {
return (
typeof value === "object" &&
value !== null &&
"name" in value && typeof value.name === "string" &&
"price" in value && typeof value.price === "number" && Number.isFinite(value.price) && value.price >= 0 &&
"tags" in value && Array.isArray(value.tags) && value.tags.every((tag) => typeof tag === "string")
);
}
const products = incoming.filter(isProduct); // Product[]
console.log(products.map((p) => p.name).join(", ")); // Lamp, Mug
function assertProduct(value: unknown): asserts value is Product {
if (!isProduct(value)) throw new Error("invalid product");
}
for (const value of [incoming[0], incoming[1]]) {
try {
assertProduct(value);
console.log(`${value.name} costs ${value.price}`); // value: Product
} catch (error) {
console.log(error instanceof Error ? error.message : error);
}
}
const mystery: unknown = incoming[0];
// @ts-expect-error -- unknown must be narrowed before use
console.log(mystery.price);Summary
- A type predicate return type
value is Tturns a boolean function into a narrowing check. array.filter(isT)with a type guard returnsT[]; TypeScript can also infer simple predicates likex => x !== undefined.- Assertion functions (
asserts value is T) throw when the check fails and narrow everything after the call. - TypeScript trusts your predicate — if the function’s logic is wrong, the types will be wrong too, so test guards.
- For complex data, a schema library generates guards for you (see Validating external data).