TypeScript Reference ยท Type Operators
TypeScript assertion functions (asserts)
Reference for TypeScript assertion functions: asserts condition and asserts x is T narrow values by throwing, with rules for declaring and calling them.
An assertion function checks something and throws if the check fails. Its return type, asserts condition or asserts value is Type, tells TypeScript that if the call returns normally, the condition holds or the value has that type. The code after the call is narrowed.
This is the throwing counterpart of a type predicate. Instead of branching on a boolean, you write the call as a statement and continue with the narrowed type.
function assertString(v: unknown): asserts v is string { if (typeof v !== "string") throw new TypeError("not a string"); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
function assertCondition(condition: unknown): asserts condition { ... } function assertType(value: unknown): asserts value is Type { ... }
| Form | Description |
|---|---|
asserts condition |
After a normal return, the argument passed for condition is treated as truthy, so its narrowing applies. |
asserts param is T |
After a normal return, the argument is narrowed to T. |
Returns: the function has no value; its return type is effectively void. It either returns normally or throws.
Errors: TypeScript does not verify the body. If the implementation never throws, the narrowing is a lie.
Usage notes
- Explicit type required at the call site. Every name in the call must have an explicit type annotation. Calling an assertion function through an untyped
const f = ...produces error 2775 ("Assertions require every name in the call target to be declared with an explicit type annotation"). - Control flow: the narrowing starts on the statement after the call and holds until the variable is reassigned.
- Node's
assertis declared with assertion signatures in@types/node, soassert(x !== undefined)narrowsx. - Choose predicates when you branch, assertions when failure is an error and you do not want an
ifaround everything. - Runtime cost: the check runs each time, so avoid heavy validation in hot paths.