User-Defined Type Guard Functions
Write is predicates to create custom type guards.
Welcome
User-defined type guards let you encapsulate a narrowing check into a reusable function using the `is` predicate return type.
The is Predicate Return Type
A type guard function returns `paramName is Type`. When the function returns true, TypeScript narrows the parameter to that type.
function isString(val: unknown): val is string {
return typeof val === 'string';
}All lessons in this course
- typeof and Truthiness Narrowing
- instanceof and in Narrowing
- User-Defined Type Guard Functions
- Exhaustiveness Checking with never