Superseded by Emery.
An assertion declares that a condition be true
before executing subsequent code.
- If the condition resolves to
true
the code continues running. - If the condition resolves to
false
an error will be thrown.
Asserts that a condition is true
, ensuring that whatever condition is being checked must be true for the remainder of the containing scope.
Note: The narrow type of
boolean
is an intentional design decision.
function assert(condition: boolean, message?: string): asserts condition;
Other assertion functions may accept "truthy" and "falsy" conditions, while assert
only accepts conditions that resolve to boolean
.
The goal is to promote consideration from consumers when dealing with potentially ambiguous values like 0
or ''
, which can introduce subtle bugs.
The assert
function has a default message:
let falsyValue = '';
assert(typeof falsyValue === 'string' && falsyValue.length > 0);
// → TypeError: Assert failed
Or you can provide a custom message:
let falsyValue = -1;
assert(falsyValue >= 0, `Expected a non-negative number, but received: ${falsyValue}`);
// → TypeError: Expected a non-negative number, but received: -1
Asserts that allegedly unreachable code has been executed.
function assertNever(condition: never): never;
Use assertNever
to catch logic forks that shouldn't be possible.
function doThing(type: 'draft' | 'published') {
switch (type) {
case 'draft':
return; /*...*/
case 'published':
return; /*...*/
default:
assertNever(type);
}
}
Warning: Regardless of the condition, this function always throws.
doThing('archived');
// → Error: Unexpected call to assertNever: 'archived'
In development both assert
and assertNever
will include a debugger statement, which will pause execution to aid debugging.