Skip to content

Custom Type Guards in TypeScript

Write user-defined type guard functions with the 'x is Type' predicate for custom narrowing.

What you'll learn

  • What a type predicate (x is Type) is and how it works
  • Writing custom type guard functions for complex types
  • Using the in operator as an inline type guard
  • Combining type guards with discriminated unions

Concept

Type Predicates

A type guard is a function that returns a boolean and tells the compiler the narrowed type. You declare it with a type predicate: function isString(x: unknown): x is string. The x is string part is the predicate — it means "if this function returns true, x is a string". After calling isString(value) in an if block, TypeScript narrows value to string inside that block, just like a typeof check.

Why Custom Type Guards

Built-in narrowing (typeof, instanceof, in) only covers simple cases. For complex types — like discriminated unions, branded types, or runtime-validated shapes — you need custom guards. For example, isApiError(response) can check whether a response object has an error field and narrow the type accordingly. Custom guards make narrowing reusable and readable.

The in Operator

The in operator checks for property presence and acts as an inline type guard: if ("name" in obj) narrows obj to a type that has name. This is useful for distinguishing object shapes without a discriminant field. Combined with type predicates, the in operator lets you build sophisticated runtime checks that the compiler understands and uses for narrowing.

Example

              // Custom type guard with a type predicate.
function isString(value: unknown): value is string {
  return typeof value === "string";
}

// Type guard for a discriminated union.
type Fish = { swim: () => void };
type Bird = { fly: () => void };
type Pet = Fish | Bird;

function isFish(pet: Pet): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

// Type guard using the 'in' operator inline.
function move(pet: Pet): void {
  if ("swim" in pet) {
    pet.swim();
  } else {
    pet.fly();
  }
}

// Using the custom guard.
function process(value: unknown): string {
  if (isString(value)) {
    // value is narrowed to string here.
    return value.toUpperCase();
  }
  return "not a string";
}

console.log(process("hello"));
console.log(process(42));
            

Type predicates (x is Type) turn boolean functions into narrowing tools. Use them for complex types that typeof and instanceof cannot handle. The in operator narrows based on property presence.

Try it

  • JSON Validator

    Type guards validate JSON shapes at runtime — test your validation logic.

  • JSON Schema Validator

    JSON Schema validation mirrors type guard logic for API data.

Common mistakes

The mistake

Writing a type predicate that does not actually verify the type at runtime

The fix

The predicate (x is Type) is a claim. The function body must actually check the type. A wrong guard gives false confidence — always verify the runtime check matches the claimed type.

The mistake

Using type assertions (as) instead of type guards for narrowing

The fix

Assertions bypass checking. Type guards verify at runtime and narrow safely. Use guards when the type is genuinely uncertain, especially for unknown or any values.

Practice Custom Type Guards in TypeScript

9 exercises

Practice Custom Type Guards in TypeScript

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors