Predicate functions & satisfies operator
Write custom type guards with predicate return types and validate objects with the satisfies operator without widening.
Intro
Goal: Build predicate functions that narrow types (e.g., value is T) and use satisfies to check shapes without widening.
- Custom guards = reusable runtime checks
satisfies= compile-time shape check, preserves literals
Predicate basics
A predicate function returns x is Type. After the check, the variable is narrowed in that scope.
function isNumber(x: unknown): x is number {
return typeof x === "number"
}
function demo(a: unknown) {
if (isNumber(a)) {
// inside: a is number
return a.toFixed(2)
}
return "not a number"
}All lessons in this course
- Exhaustive switches & never checks
- Predicate functions & satisfies operator
- Refining unions across function boundaries