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 features advanced debugging options, support for various error types, and a "bypass" mode for soft warnings.
Source Code
View Source Code
ts
import type { Obj } from '../types';
type AssertOptions = { args?: Obj; bypass?: boolean; type?: ErrorConstructor };
/**
* Asserts that a condition is true. Throws (or warns, with `bypass`) otherwise.
*
* @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 } });
* assert(ok, 'not ok', { bypass: true }); // logs warning instead of throwing
* 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.
* @param [options.bypass] - Log a warning instead of throwing.
*
* @throws {Error} If `condition` is false and `bypass` is not set.
*/
export function assert(
condition: boolean,
message = 'Assertion failed',
{ args, bypass = false, type = Error }: AssertOptions = {},
): void {
if (condition) return;
const errorDetails = args ? `\nArguments: ${JSON.stringify(args, null, 2)}` : '';
const fullMessage = `${message}${errorDetails}`;
if (bypass) console.warn(fullMessage);
else 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.
- Soft Assertions: Use
bypassmode to log warnings instead of throwing.
API
ts
function assert(
condition: boolean | boolean[],
message?: string,
options?: {
type?: ErrorConstructor;
args?: Record<string, any>;
bypass?: boolean;
},
): 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.bypass: Iftrue, logs a warning to the console instead of throwing an exception.
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 },
});
}Soft Assertion (Bypass)
ts
import { assert } from '@vielzeug/toolkit';
// Logs warning instead of crashing the app
assert(isLoaded, 'Not loaded yet, continuing anyway...', { bypass: true });Implementation Notes
- If an array of conditions is provided, it returns
trueonly if every item is truthy. - In
bypassmode, it usesconsole.warnto log the failure. - Performance is optimized for minimal overhead when assertions pass.
See Also
- assertParams: Validate function arguments against types.
- attempt: Safely execute logic and ignore errors.
- isDefined: Common check used within assertions.