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.
In more detail
After assertDefined(orderId, "Order ID is required"), the rest of the function knows orderId is a string, with no if block needed. It must return nothing and throw on failure. This flattens code that would otherwise nest many if statements.
Example
function assertDefined<T>(val: T, msg: string): asserts val is NonNullable<T>Related terms
- type predicate — A return type written param is Type, which tells the compiler that when the function returns true, the argument has that type.
- invariant — A rule that must always hold for an object or system, such as a count never being negative.
- try...catch — A statement that runs code in a try block and, if that code throws an exception, runs a catch block instead of crashing.
- type narrowing — The compiler refining a broad type to a more specific one inside a block, after a check proves which case applies.
Taught in
- 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