type predicate
A return type written param is Type, which tells the compiler that when the function returns true, the argument has that type.
In more detail
A plain boolean function tells the caller nothing. function isNotNull<T>(val: T | null | undefined): val is T lets array.filter(isNotNull) produce a clean array of T. The compiler trusts the predicate, so its check must really be correct.
Example
function isObject(val: unknown): val is Record<string, unknown>Related terms
- type guard — A run time check, such as typeof x === "string" or a custom function, that the compiler uses to narrow a type.
- assertion function — A function whose return type is asserts condition or asserts val is Type, which throws if the check fails and otherwise narrows the caller's code.
- type narrowing — The compiler refining a broad type to a more specific one inside a block, after a check proves which case applies.
- Boolean — A value that can only be true or false.
Taught in
- Why TypeScript: Contracts, Erased Types And Soundness — Production TypeScript
- The in Operator And Instanceof Narrowing — Production TypeScript
- Custom Type Predicates: Functions Returning is Type — Production TypeScript
- Assertion Signatures: asserts condition And Invariants — Production TypeScript
- Exhaustive Narrowing With never In Production Handlers — Production TypeScript