Type Predicate and Assertion Pitfalls
What you'll learn: How to recognize and avoid the dangerous gap between runtime checks and the type guarantees you claim with predicates and assertions.
The Core Problem
Type predicates and assertion functions are promises you make to TypeScript about what's true at runtime. But TypeScript trusts you completely — it doesn't verify that your runtime logic actually proves the type claim you're making. This creates a dangerous opportunity for false positives: cases where TypeScript narrows the type based on your predicate, but the actual runtime value doesn't match.
The Pitfall in Action
Think of it like a security guard at a concert. You write a function that's supposed to check if someone has a VIP pass. If your checking logic is incomplete (maybe you only check that they're holding something shiny), your assertion "yes, they're VIP" might be wrong — but TypeScript will believe you and let them through anyway.
The Danger Zone
function isNumber(value: unknown): value is number {
return value !== null; // ❌ BAD: doesn't actually check for number!
}
const x: unknown = "hello";
if (isNumber(x)) {
// TypeScript thinks x is number here
const doubled = x * 2; // Runtime error! x is actually a string
}
Your predicate said "this is a number" but only checked "this isn't null." TypeScript trusted your claim, creating a type-safety hole.
Avoiding the Pitfall
Always ensure your runtime check truly guarantees the type you're claiming. If you say value is number, you must actually verify typeof value === 'number'.
Key Takeaway: Type predicates and assertions transfer responsibility from TypeScript to you — ensure your runtime checks completely validate the types you claim, or you'll create dangerous false positives that defeat type safety.