Course contentsShow
← TypeScript
Lesson 225 of 1,7965. Type Narrowing FundamentalsFree lesson

Writing Reliable Type Predicates

Ensuring your type predicate logic actually matches the type claim to avoid runtime errors.

Writing Reliable Type Predicates

What you'll learn: How to ensure your type predicate functions don't lie about the types they claim to narrow.

The Trust Problem

A type predicate is a promise you make to TypeScript: "If this function returns true, the value is definitely this type." TypeScript trusts you completely — it won't verify that your logic actually matches your claim. This means you can accidentally lie to the compiler, leading to runtime errors that TypeScript thought were impossible.

Making Your Predicates Trustworthy

When you write a type predicate, your function body must rigorously test for every characteristic of the type you're claiming. Missing even one property check means TypeScript will treat unsafe values as safe.

interface Cat {
  meow: () => void;
  whiskers: number;
}

// ❌ UNRELIABLE: Only checks one property
function isCat(pet: unknown): pet is Cat {
  return typeof pet === 'object' && pet !== null && 'meow' in pet;
}

// ✅ RELIABLE: Checks everything Cat requires
function isCat(pet: unknown): pet is Cat {
  return (
    typeof pet === 'object' &&
    pet !== null &&
    'meow' in pet &&
    typeof pet.meow === 'function' &&
    'whiskers' in pet &&
    typeof pet.whiskers === 'number'
  );
}

The unreliable version will cause runtime errors if you pass an object with meow but no whiskers — TypeScript won't catch it because you told it the check was sufficient.

The Verification Checklist

For each type predicate, verify:

  • You check all required properties exist
  • You validate the types of those properties
  • Your logic handles null and undefined
  • Edge cases won't slip through

Key Takeaway: Type predicates are contracts you enforce manually — TypeScript assumes your checks are complete, so incomplete validation creates silent runtime dangers.