Custom type guards

Topic 5 of 5 in Unions and narrowing7 min readIntermediateFree course

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

TypeScript
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

Custom type guards. function isCat(pet: Cat | Dog): pet is Cat { return “meow” in pet; } — the return type pet is Cat is a type predicate: “if I return true, pet is a Cat”. With is, the narrowing happens in if/else: if (isCat(pet)) { pet.meow(); } gives pet: Cat, and the else branch gives pet: Dog. With asserts, the narrowing happens after the call: function assertCat(pet: Cat | Dog): asserts pet is Cat { … throw … }; then after assertCat(pet); pet.meow() works because pet is Cat from there on.

Change the return type to a type predicate:

TypeScript
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:

TypeScript
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:

TypeScript
const valid = items.filter(isUser);   // User[]

Since TypeScript 5.5, simple predicates are inferred automatically — you don’t even need to write the guard:

TypeScript
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:

TypeScript
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 on

The 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:

TypeScript
function assert(condition: unknown, message: string): asserts condition {
  if (!condition) throw new Error(message);
}

assert(user !== undefined, "user must be loaded");
user.name;   // narrowed

One 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:

TypeScript
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:

TypeScript
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 T for checks used in if and filter; asserts value is T for “check or throw”; and test your guards, because TypeScript believes them.

Exercise

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.

TypeScript
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()

Summary

  • A type predicate return type value is T turns a boolean function into a narrowing check.
  • array.filter(isT) with a type guard returns T[]; TypeScript can also infer simple predicates like x => 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).