What Type Predicates Are
You'll learn what type predicates are and why they enable more powerful type narrowing than built-in guards.
The Problem with Boolean Returns
So far, you've used typeof, instanceof, and in to narrow types — these are built-in guards. But what if you write your own function to check a type? A normal boolean return doesn't help TypeScript narrow:
function isString(value: unknown): boolean {
return typeof value === "string";
}
let input: string | number = "hello";
if (isString(input)) {
// TypeScript still sees: string | number
// It doesn't know isString narrows the type!
}
TypeScript loses track of the narrowing inside your custom function.
Introducing Type Predicates
A type predicate is a special return type for functions that tells TypeScript exactly what type a value has when the function returns true. The syntax is parameterName is Type:
function isString(value: unknown): value is string {
return typeof value === "string";
}
let input: string | number = "hello";
if (isString(input)) {
// TypeScript now knows: input is string here
console.log(input.toUpperCase());
}
The value is string return type means: "If this function returns true, then value is definitely a string."
The Anatomy
- Parameter name (
value) must match the function's parameter iskeyword connects the parameter to its narrowed type- Target type (
string) is what you're confirming
Think of it like a truth stamp: your function promises TypeScript that when it returns true, the checked value has that specific type.
Key Takeaway: Type predicates (value is Type) let you create custom type guards that preserve type narrowing across function boundaries, something plain boolean returns can't do.