Type Predicates
What
Type predicates allow you to create custom functions that narrow a type when they return true.
How
You define a function with a special return type in the format parameter is Type:
function isString(val: unknown): val is string {
return typeof val === "string";
}
const x: unknown = "hello";
if (isString(x)) {
// x is now narrowed to string
console.log(x.toUpperCase());
}
Why
Type predicates are useful when the logic to check a type is complex or involves multiple property checks. By encapsulating this logic in a function, you make your narrowing code cleaner, more readable, and easier to reuse throughout your application.
Summary
Use type predicates to build powerful, reusable narrowing logic for complex data structures.