Define functions that narrow types by throwing on invalid input.
Assertion functions are functions whose return type is annotated with asserts condition or asserts param is Type. When called, they either throw an error or return normally. If they return normally, TypeScript narrows the type of the asserted value in subsequent code.
Unlike type guard functions that return a boolean and require an if statement for narrowing, assertion functions narrow the type for all code that follows the call. This makes them ideal for validation at the top of functions.
Assertion functions must explicitly throw or call another assertion function on all code paths that do not satisfy the assertion. They are commonly used for input validation, invariant checks, and ensuring preconditions in function bodies.
function assertIsString(val: unknown): asserts val is string {
if (typeof val !== 'string') {
throw new Error(`Expected string, got ${typeof val}`);
}
}
function process(input: unknown) {
assertIsString(input);
// input is now narrowed to string
console.log(input.toUpperCase());
}