assert
The assert utility validates conditions during runtime. If a condition (or any condition in a list) is false, it throws a customizable error. It supports advanced debugging options and custom error types.
Source Code
View Source Code
ts
import type { Obj } from '../types';
type AssertOptions = { args?: Obj; type?: ErrorConstructor };
/**
* Asserts that a condition is true.
*
* @example
* ```ts
* assert(Array.isArray([])); // ok
* assert(x > 0, 'x must be positive'); // throws if false
* assert(x > 0, 'x must be positive', { args: { x } });
* assertAll([cond1, cond2], 'One failed'); // throws if any is false
* ```
*
* @param condition - The boolean condition to assert.
* @param [message] - Error message (default: `'Assertion failed'`).
* @param [options.type] - Error class to throw (default: `Error`).
* @param [options.args] - Debugging info appended to the message.
* @throws {Error} If `condition` is false.
*/
export function assert(
condition: boolean,
message = 'Assertion failed',
{ args, type = Error }: AssertOptions = {},
): void {
if (condition) return;
const errorDetails = args ? `\nArguments: ${JSON.stringify(args, null, 2)}` : '';
const fullMessage = `${message}${errorDetails}`;
throw new type(fullMessage);
}
/**
* Asserts that every condition in the array is true.
*
* @example
* ```ts
* assertAll([cond1, cond2, cond3], 'One or more conditions failed');
* ```
*/
export function assertAll(conditions: boolean[], message = 'Assertion failed', options: AssertOptions = {}): void {
assert(conditions.every(Boolean), message, options);
}Features
- Isomorphic: Works in both Browser and Node.js.
- Multiple Conditions: Pass a single boolean or an array of conditions.
- Customizable Errors: Specify the error message and the Error class to throw (e.g.,
TypeError). - Debugging Info: Attach metadata to errors for easier troubleshooting.
API
ts
function assert(
condition: boolean | boolean[],
message?: string,
options?: {
type?: ErrorConstructor;
args?: Record<string, any>;
},
): void;Parameters
condition: A boolean or an array of booleans to check.message: Optional. The error message to display (defaults to'Assertion failed').options: Optional configuration:type: The constructor of the error to throw (defaults toError).args: An object containing variables or state to include in the error details.
Returns
void(Nothing) if the assertion passes.
Examples
Basic Validation
ts
import { assert } from '@vielzeug/toolkit';
assert(1 + 1 === 2); // OK
assert(users.length > 0, 'Users list cannot be empty'); // Throws if emptyAdvanced Debugging
ts
import { assert } from '@vielzeug/toolkit';
function process(data: any) {
assert(data.id, 'Missing ID', {
type: TypeError,
args: { received: data },
});
}Implementation Notes
- If an array of conditions is provided, it returns
trueonly if every item is truthy. - Performance is optimized for minimal overhead when assertions pass.