Assertion Functions vs Type Predicates
What you'll learn: When to throw errors with assertion functions versus when to return boolean checks with type predicates.
The Core Difference
Both assertion functions and type predicates help TypeScript narrow types, but they handle invalid cases differently:
- Type predicates return
trueorfalse, letting you decide what to do with the information - Assertion functions throw an error immediately if the condition fails, stopping execution
Think of it like security checkpoints: a type predicate is like a scanner that tells you "yes" or "no" so you can choose another route. An assertion function is like a bouncer that physically stops you if you don't pass.
When to Use Type Predicates
Use type predicates when:
- You want to filter or branch based on type
- Failure is an expected, normal case you'll handle
- You're processing arrays where some items might not match
- The caller should decide what happens on failure
function isString(value: unknown): value is string {
return typeof value === 'string';
}
// Caller controls the flow
if (isString(data)) {
console.log(data.toUpperCase());
} else {
console.log('Not a string, doing something else');
}
When to Use Assertion Functions
Use assertion functions when:
- The value must be a certain type or the program can't continue
- Failure indicates a programming error, not expected input
- You want to crash early rather than propagate bad data
- You're validating critical assumptions
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== 'string') {
throw new Error('Value must be string');
}
}
// After this line, TypeScript knows value is string
assertIsString(data);
console.log(data.toUpperCase()); // No if check needed
Key Takeaway: Use type predicates for flexible branching logic; use assertion functions when the wrong type means something is seriously broken and execution should stop.