assert function
Throws when a condition is falsy, and narrows its type otherwise.
ts
import { assert } from 'utils';Signature
ts
export function assert(condition: unknown, message = 'Assertion failed'): asserts conditionParameters
| Name | Description |
|---|---|
condition | The value that must be truthy. |
message | The message of the error. Defaults to 'Assertion failed'. |
Errors
- Throws Error: When
conditionis falsy.
Example
ts
assert(user !== undefined, 'User not loaded');
user.name; // `user` is no longer `undefined`Tests
Line coverage: 100 %.
- ✅ passes for the truthy value true
- ✅ passes for the truthy value 1
- ✅ passes for the truthy value "text"
- ✅ passes for the truthy value {}
- ✅ passes for the truthy value undefined
- ✅ throws for the falsy value false
- ✅ throws for the falsy value 0
- ✅ throws for the falsy value
- ✅ throws for the falsy value undefined
- ✅ throws for the falsy value undefined
- ✅ throws for the falsy value NaN
- ✅ throws "Assertion failed" by default
Source
src/guard/assert.ts (on GitHub)
Source code
ts
/**
* Throws when a condition is falsy, and narrows its type otherwise.
*
* @param condition - The value that must be truthy.
* @param message - The message of the error. Defaults to `'Assertion failed'`.
* @throws {Error} When `condition` is falsy.
* @example
* assert(user !== undefined, 'User not loaded');
* user.name; // `user` is no longer `undefined`
*/
export function assert(condition: unknown, message = 'Assertion failed'): asserts condition {
const isTruthy = Boolean(condition);
if (!isTruthy) {
throw new Error(message);
}
}Test file
ts
import { assert } from './assert';
const checkAssert: (condition: unknown, message: string) => void = assert;
describe(assert, () => {
it.for([true, 1, 'text', {}, []])('passes for the truthy value %j', (condition) => {
expect(() => {
checkAssert(condition, 'Assertion failed');
}).not.toThrow();
});
it.for([false, 0, '', null, undefined, NaN])('throws for the falsy value %s', (condition) => {
expect(() => {
checkAssert(condition, 'Boom');
}).toThrow('Boom');
});
it('throws "Assertion failed" by default', () => {
expect(() => {
assert(false);
}).toThrow('Assertion failed');
});
});Keywords: assert, guards, function