Narrowing with Type Predicates
What you'll learn: How TypeScript uses your custom type predicate functions in conditional statements to automatically refine types in the true branch.
When you write a type predicate function (one that returns parameterName is Type), TypeScript doesn't just see it as a function returning a boolean. It treats it as a type guard that actively narrows types based on your conditional logic.
How Type Predicates Enable Narrowing
Think of type predicates as giving TypeScript "insider information." When you call a type predicate function in an if statement, TypeScript trusts your judgment: if the function returns true, it automatically narrows the type in that branch.
function isString(value: unknown): value is string {
return typeof value === 'string';
}
let myValue: string | number = getSomeValue();
if (isString(myValue)) {
// TypeScript KNOWS myValue is a string here
console.log(myValue.toUpperCase()); // ✓ string methods available
} else {
// TypeScript KNOWS myValue is a number here
console.log(myValue.toFixed(2)); // ✓ number methods available
}
Why This Matters
Without the type predicate (just returning boolean), TypeScript wouldn't narrow the type. The predicate creates a contract: "If this function returns true, you can trust that the value is this specific type."
The narrowing happens in:
- The
ifblock (true branch) - The
elseblock (TypeScript eliminates the predicate type) - Any code path where the predicate succeeds
Key Takeaway: Type predicates turn ordinary functions into powerful type guards that TypeScript uses to automatically narrow types in true branches, giving you full type safety without manual casting.