- Courses
- đź’»Programming Languages
- 🛡️TypeScript
- Narrowing, Guards & Control Flow Analysis
- Custom Type Guards
On this page
TypeScript Custom Type Guards: Complete Guide
Published on August 1, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Custom type guards are user‑defined functions that tell TypeScript how to narrow a type based on runtime checks. They are functions that return a type predicate — a special return type annotation written as value is Type. When such a function returns true, TypeScript treats the value as the specified type within that scope. This bridges the gap between runtime validation and compile‑time type safety, enabling you to safely handle unknown data from APIs, user input, or JSON parsing. Custom type guards are one of TypeScript's most powerful features for building robust applications, as they combine runtime checks with static analysis guarantees.
What Are Type Guards?​
A type guard is an expression that performs a runtime check and guarantees the type of a value within a specific scope. Built‑in type guards include:
typeof— checks primitive types like"string","number","boolean"instanceof— checks if an object is an instance of a specific classin— checks if a property exists on an object
These built‑in guards work well for simple cases. However, real‑world applications often need to validate complex object shapes, nested structures, or data from external sources where the exact type is not known at compile time. Custom type guards solve this problem by allowing you to define your own narrowing logic.
The Problem: Unsafe Type Handling​
Consider this common scenario where unsafe type handling creates runtime failures:
type ApiResponse =
| { success: true; data: { id: string; name: string } }
| { success: false; error: string };
function processResponse(response: ApiResponse) {
// ❌ Unsafe: assumes success without checking
const data = (response as any).data;
console.log(`Processing user: ${data.name}`);
return data.id;
}
This code compiles without warnings because as any bypasses all type checking. When called with an error response, it crashes at runtime with Cannot read properties of undefined. Custom type guards provide a safe alternative that TypeScript understands and enforces.
Writing a Custom Type Guard: The value is Type Syntax​
To define a custom type guard, write a function whose return type is a type predicate — parameterName is Type. The function body performs the runtime checks and returns a boolean.
function isString(value: unknown): value is string {
return typeof value === "string";
}
The type predicate value is string tells TypeScript that if isString(value) returns true, value is a string within that scope.
Using a Type Guard​
function printUpper(value: unknown) {
if (isString(value)) {
// âś… TypeScript knows value is string here
console.log(value.toUpperCase());
} else {
console.log("Not a string");
}
}
Without the guard, TypeScript would not allow value.toUpperCase(). The guard enables safe property access.
Type Guards for Objects​
Custom type guards become essential when validating object shapes from external data.
Guarding a User Object​
type User = {
id: number;
name: string;
};
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof (value as any).id === "number" &&
"name" in value &&
typeof (value as any).name === "string"
);
}
The guard checks that the value is a non‑null object and contains the required properties with the correct types.
Using the Guard with External Data​
const data: unknown = JSON.parse('{"id":1,"name":"Alice"}');
if (isUser(data)) {
// ✅ data is User here — safe to access
console.log(data.name.toUpperCase());
}
This pattern prevents entire classes of runtime bugs when working with data from APIs, files, or user input.
Type Guards for Arrays​
You can validate arrays and their contents using custom type guards.
Guarding an Array of Strings​
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((item) => typeof item === "string");
}
Guarding an Array of Objects​
function isUserArray(value: unknown): value is User[] {
return Array.isArray(value) && value.every((item) => isUser(item));
}
This composable approach — using one guard inside another — makes it easy to validate complex nested data structures.
Type Guards for Discriminated Unions​
Discriminated unions (tagged unions) benefit greatly from custom type guards.
Defining a Discriminated Union​
type Success = { status: "success"; data: string };
type Failure = { status: "error"; error: Error };
type Result = Success | Failure;
Writing a Guard for the Union​
function isSuccess(result: Result): result is Success {
return result.status === "success";
}
Using the Guard​
function handleResult(result: Result) {
if (isSuccess(result)) {
// ✅ result is Success — data is safe to access
console.log(result.data.toUpperCase());
} else {
// ✅ result is Failure — error is safe to access
console.error(result.error.message);
}
}
This is cleaner and more reusable than repeating result.status === "success" checks everywhere.
Type Guards with Generic Constraints​
For reusable validation, you can create generic type guards:
function hasProperty<K extends string>(obj: unknown, prop: K): obj is Record<K, unknown> {
return typeof obj === "object" && obj !== null && prop in obj;
}
This guard checks whether an object has a specific property, narrowing the type to Record<K, unknown>.
Best Practices for Custom Type Guards​
Use descriptive names — name predicate functions clearly, like isUser, isProduct, or hasContactInfo.
Keep predicates focused — check one specific aspect of a type rather than bundling unrelated checks.
Start with unknown, not any — using unknown forces you to validate the value properly.
Validate recursively for nested data — use one guard inside another to validate complex structures.
Consider runtime validation libraries for large applications — libraries like zod or io-ts provide schema‑based validation with type inference.
Putting It All Together​
Here is a realistic example combining multiple guard techniques:
type User = {
id: number;
name: string;
roles: string[];
};
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
typeof (value as any).id === "number" &&
typeof (value as any).name === "string" &&
Array.isArray((value as any).roles) &&
(value as any).roles.every((r: unknown) => typeof r === "string")
);
}
async function loadUser(): Promise<User> {
const res = await fetch("/api/user");
const data: unknown = await res.json();
if (!isUser(data)) {
throw new Error("Invalid user data");
}
return data; // âś… TypeScript knows this is User
}
This is the exact pattern used in production systems to validate external data safely.
Summary​
Custom type guards are functions that return a type predicate (value is Type) to teach TypeScript how to narrow types based on runtime checks. They are essential for:
- Validating data from external sources (APIs, JSON, user input)
- Narrowing discriminated unions with custom logic
- Checking complex object shapes and nested structures
- Building reusable, composable validation functions
By combining runtime checks with compile‑time type safety, custom type guards eliminate the need for unsafe type assertions and catch errors before they reach production.
Frequently Asked Questions​
What is a custom type guard in TypeScript?
A custom type guard is a user-defined function that returns a type predicate (`value is Type`). When the function returns `true`, TypeScript narrows the type of the value to the specified type within that scope. This allows you to combine runtime checks with compile-time type safety.
What is the syntax for a type predicate in TypeScript?
The syntax is `parameterName is Type`. For example: `function isString(value: unknown): value is string { return typeof value === "string"; }`. The `is` keyword tells TypeScript that if the function returns `true`, the parameter is of the specified type.
How do I write a custom type guard for an object type?
Write a function that checks if the value is an object, not null, and has the required properties with the correct types. Example: `function isUser(value: unknown): value is User { return typeof value === 'object' && value !== null && 'id' in value && typeof (value as any).id === 'number' && 'name' in value && typeof (value as any).name === 'string'; }`.
What is the difference between `value is Type` and `asserts value is Type`?
`value is Type` is a type predicate that returns a boolean and narrows the type when it returns `true`. `asserts value is Type` is an assertion function that throws an error if the check fails, and narrows the type for the remaining code without requiring an `if` statement. Use `asserts` when you want to fail fast on invalid data.
Why does my custom type guard not narrow the type correctly?
Common reasons include: returning a plain boolean without a type predicate, using `any` instead of `unknown` which bypasses type checking, using `in` without checking the property type, or having incomplete checks that allow invalid values. Also, ensure the guard is called inside a conditional block like `if` or a ternary expression.
Can I use custom type guards with discriminated unions?
Yes. Write a guard that checks the discriminant property. For example: `function isSuccess(result: Result): result is Success { return result.status === 'success'; }`. TypeScript narrows the union to the specific member when the guard returns `true`.
How do I write a type guard for an array of objects?
Combine `Array.isArray()` with `every()` using the object guard. Example: `function isUserArray(value: unknown): value is User[] { return Array.isArray(value) && value.every((item) => isUser(item)); }`. This validates both the array structure and its contents.
Can I create a type guard that checks for multiple possible types?
Yes. Use a type guard that returns a union of types. For example: `function isStringOrNumber(value: unknown): value is string | number { return typeof value === 'string' || typeof value === 'number'; }`. After the guard, you can further narrow with `typeof` checks.
What is the difference between a type guard and a type assertion?
A type guard is a runtime check that proves a value has a certain type, and TypeScript respects it for type narrowing. A type assertion (`as Type`) is a compile-time instruction that tells TypeScript to treat a value as a specific type without any runtime guarantee. Type guards are safer because they perform actual checks.
Can custom type guards be used with generic types?
Yes. You can write generic type guards like `function hasProperty<T extends string>(obj: unknown, prop: T): obj is Record<T, unknown> { return typeof obj === 'object' && obj !== null && prop in obj; }`. The type predicate can reference the generic type parameter.
What is the recommended approach for validating external API data with type guards?
Always treat external data as `unknown` when it arrives (e.g., from `fetch().json()`). Write custom type guards that validate the shape and types of the data. Use these guards in conditional blocks before accessing the data. For large applications, consider using a runtime validation library like `zod` that automatically generates type guards from schemas.
How do I debug a type guard that is not working as expected?
Add `console.log()` statements inside the guard to inspect the value and its properties. Use the TypeScript Playground with the `--strict` flag to see how TypeScript infers the type. Simplify the guard to test each condition separately. Check that you are using `unknown` and not `any`, which would bypass all checks.
Can I use `typeof` and `instanceof` inside custom type guards?
Yes. Custom type guards can use any runtime JavaScript check, including `typeof` for primitives, `instanceof` for class instances, `in` for property existence, `Array.isArray()`, and custom validation logic. The function body is just JavaScript — any check that proves the type works.
What is the performance impact of using custom type guards?
Type guards are executed at runtime and the performance impact is proportional to the complexity of the checks. Simple guards (like `typeof`) are negligible. Complex guards that recursively validate deeply nested objects may be slower, but in most cases the performance cost is acceptable for the safety they provide.
How do I use a type guard to check for optional properties?
Check for optional properties using `in` or `hasOwnProperty` to see if the property exists. If it exists, validate its type. If it doesn't, the check passes the guard but the property may be `undefined`. Example: `if ('email' in value) { typeof (value as any).email === 'string' }` ensures `email` is a string when present.
Can I use custom type guards with class instances?
Yes. Use `instanceof` inside the guard to check the class. Example: `function isDog(value: unknown): value is Dog { return value instanceof Dog; }`. This works with custom classes and built-in classes like `Date`, `Error`, or `RegExp`.
What is the difference between a type guard and a type narrowing function?
The terms are often used interchangeably. A type guard specifically refers to a function that returns a type predicate (`value is Type`). Type narrowing is the broader concept where TypeScript refines a type based on any conditional logic — `if` statements, `switch` cases, truthiness checks, `typeof`, `instanceof`, `in`, and custom type guards.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Type Narrowing
Next
Exhaustiveness Checking
-
What Are Type Guards?
-
The Problem: Unsafe Type Handling
-
Writing a Custom Type Guard: The
value is TypeSyntax- Using a Type Guard
-
Type Guards for Objects
- Guarding a User Object
- Using the Guard with External Data
-
Type Guards for Arrays
- Guarding an Array of Strings
- Guarding an Array of Objects
-
Type Guards for Discriminated Unions
- Defining a Discriminated Union
- Writing a Guard for the Union
- Using the Guard
-
Type Guards with Generic Constraints
-
Best Practices for Custom Type Guards
-
Putting It All Together
-
Summary
-
Frequently Asked Questions
