An assertion function (TS 3.7+) has a return type of asserts condition or asserts value is T. If it returns normally, TypeScript narrows the type for the rest of the scope. If the condition is false, the function must throw. It's the "fail fast" counterpart to a type guard (value is T, which returns a boolean you branch on). Use them for invariants, preconditions and validating external data at the start of a function, so the following code stays flat and fully typed.
// 1. asserts condition: like Node's assert()
function assert(condition: unknown, message = 'Assertion failed'): asserts condition {
if (!condition) throw new Error(message);
}
function getTotal(order: Order | undefined) {
assert(order, 'order is required');
return order.items.length; // order: Order
}
// 2. asserts value is T
function assertIsString(value: unknown, name = 'value'): asserts value is string {
if (typeof value !== 'string') throw new TypeError(`${name} must be a string`);
}
function greet(input: unknown) {
assertIsString(input, 'input');
return input.toUpperCase(); // input: string
}
// Type guard: caller decides what to do
if (isUser(data)) { render(data) } else { showError() }
// Assertion: invalid data is exceptional; just throw
assertIsUser(data);
render(data);
Use a guard when both outcomes are normal control flow. Use an assertion when failure means a bug or corrupted input that should stop execution.
assertDefined(map.get(id)).never.schema.parse() throws and returns typed data, which serves the same purpose).assertIsError(err) before checking err.message.function assertElement<T extends Element>(
el: Element | null,
ctor: new () => T,
): asserts el is T {
if (!(el instanceof ctor)) throw new Error(`Expected ${ctor.name}`);
}
const canvas = document.querySelector('#chart');
assertElement(canvas, HTMLCanvasElement);
canvas.getContext('2d');
const whose type is inferred can't be used as an assertion:const assertNum = (v: unknown): asserts v is number => { /* ... */ };
assertNum(x); // error TS2775: the variable itself needs an explicit type annotation
type AssertNum = (v: unknown) => asserts v is number;
const assertNum2: AssertNum = v => { if (typeof v !== 'number') throw new Error(); };
assertNum2(x); // OK
Declaring it with function, or giving the variable an explicit function type, avoids "Assertions require every name in the call target to be declared with an explicit type annotation."
async. The narrowing only applies synchronously. asserts return types can't be combined with Promise.console.assert, which doesn't throw.asserts cond and asserts x is T narrow after the call, or throw.parse), DOM queries, tests.Spotted a mistake or a rights concern? Report an issue