Type Predicates for Custom Narrowing with unknown
What you'll learn: How to write user-defined type guards that narrow unknown values to specific interfaces or type shapes.
The Problem This Solves
You've learned many built-in narrowing techniques (typeof, instanceof, in), but sometimes you need to check if an unknown value matches a custom interface or complex shape. Built-in operators can't express "this object has properties x and y both as numbers." That's where user-defined type predicates come in.
What Are Type Predicates?
A type predicate is a special return type annotation in the form parameterName is Type. When a function returns true, TypeScript narrows the parameter to that type in the calling scope.
function isPoint(value: unknown): value is { x: number; y: number } {
return (
typeof value === "object" &&
value !== null &&
"x" in value &&
typeof (value as any).x === "number" &&
"y" in value &&
typeof (value as any).y === "number"
);
}
Now you can safely narrow unknown:
function processValue(input: unknown) {
if (isPoint(input)) {
// TypeScript knows input is { x: number; y: number }
console.log(input.x + input.y);
}
}
Why This Matters for unknown
unknown forces you to prove what you have before using it. Type predicates let you encode validation logic once and reuse it everywhere, making unknown practical in real applications like parsing JSON or validating external data.
The Pattern
- Accept
unknownas the parameter - Perform runtime checks (typeof, in, etc.)
- Return
parameterName is SpecificType - TypeScript trusts your logic and narrows accordingly
Key Takeaway: Type predicates let you create reusable, type-safe validators that teach TypeScript how to narrow unknown to your custom interfaces and complex shapes.