asserts

Declares an assertion function that narrows types by throwing on failure.

Since TS 3.7 Spec ↗

Syntax

function fn(x: unknown): asserts x is Type

Examples

function assertString(x: unknown): asserts x is string {
  if (typeof x !== 'string') throw new Error('not a string');
}

function use(v: unknown) {
  assertString(v);
  v.toUpperCase(); // v is string here
}
function assert(cond: unknown): asserts cond {
  if (!cond) throw new Error('assertion failed');
}

Notes

An `asserts` return type signals that the function returns normally only when the condition holds; otherwise it throws. After the call the compiler narrows the argument. `asserts cond` narrows the condition to truthy; `asserts x is T` narrows to a specific type.

See also