Menu

Type Predicates and Assertion Functions

Lesson 4: Type Predicates and Assertion Functions

When do you need a custom guard?

Built-in checks cover most cases. When a check is complex or reused, put it in a function and tell TypeScript what it proves.

Tool Signature Effect
Type predicate (x: unknown): x is Product Narrows inside if (isProduct(x))
Assertion function (x: unknown): asserts x is Product Narrows all code after the call; throws otherwise
Assert condition (cond: unknown, msg: string): asserts cond Narrows based on any condition

Example

type Product = { id: string; name: string; price: number };

function isProduct(value: unknown): value is Product {
  return (
    typeof value === 'object' &&
    value !== null &&
    typeof (value as Record<string, unknown>).id === 'string' &&
    typeof (value as Record<string, unknown>).name === 'string' &&
    typeof (value as Record<string, unknown>).price === 'number'
  );
}

const data: unknown = JSON.parse(raw);
if (isProduct(data)) {
  console.log(data.name); // data: Product
}

// Assertion function
function assertIsDefined<T>(value: T, name: string): asserts value is NonNullable<T> {
  if (value === undefined || value === null) {
    throw new Error(`${name} is required`);
  }
}

const address = customer.address; // Address | undefined
assertIsDefined(address, 'Delivery address');
address.pincode; // address: Address

Inferred type predicates: TypeScript can infer simple predicates for you, which makes filter precise:

const maybePrices: (number | null)[] = [6400, null, 64500];
const prices = maybePrices.filter((p) => p !== null); // number[]

How it works

  • value is Product is a promise to the compiler. TypeScript trusts it, so the function body must really check every field.
  • Assertion functions narrow everything after the call, which keeps code flat instead of nested in if blocks.
  • For larger shapes, a schema library such as Zod generates these checks for you (Module 10).

Common mistakes

Mistake Effect Fix
A predicate that checks too little Wrong data treated as valid Check every required field, or use a schema library
Using an assertion function as an arrow function without a type annotation Error: assertions require explicit annotations Declare it with function or annotate the variable
Writing guards for types TypeScript already narrows Extra code Use built-in checks where they suffice

Key takeaways

  • Type predicates (x is T) and assertion functions (asserts x is T) teach TypeScript about your own checks.
  • They are only as safe as the checks inside them.

Try it: Write an isCartItem predicate and use it to filter a unknown[] array loaded from local storage into CartItem[].


TypeScript Tutorial

J

Jebasta





Get in Touch For Details