Skip to content
VersionSize

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.

Implementation

View Source Code
ts
import { Logit } from '@vielzeug/logit';
import type { Obj } from '../types';

/**
 * Asserts that the condition is true. If the condition is false, it throws an error
 * with the provided message or logs a warning in soft mode.
 *
 * @example
 * ```ts
 * assert(Array.isArray([])); // Does nothing
 * assert(typeof foo === 'string', 'This is an error message'); // Throws an error
 * assert(x > 0, 'x must be positive', { args: { x } }); // Throws with argument details
 * ```
 *
 * @param condition - The condition to assert, or an array of conditions.
 * @param [message] - The error message to throw. Default is 'Assertion failed'.
 * @param options - Assertion options.
 * @param [options.type] - The error class to throw (default: `Error`).
 * @param [options.args] - Additional debugging information (e.g., variable values).
 * @param [options.bypass] - If `true`, logs a warning instead of throwing an error.
 *
 * @throws {Error} If the condition is false and `bypass` is not set to `true`.
 */
export function assert(
  condition: boolean | boolean[],
  message = 'Assertion failed',
  { type = Error, args, bypass = false }: { type?: ErrorConstructor; args?: Obj; bypass?: boolean } = {},
): void {
  const failed = Array.isArray(condition) ? condition.some((cond) => !cond) : !condition;
  if (!failed) return;

  const errorDetails = args ? `\nArguments: ${JSON.stringify(args, null, 2)}` : '';
  const fullMessage = `${message}${errorDetails}`;

  if (bypass) Logit.warn(fullMessage);
  else throw new type(fullMessage);
}

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 bypass mode 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 to Error).
    • args: An object containing variables or state to include in the error details.
    • bypass: If true, 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 empty

Advanced 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 true only if every item is truthy.
  • In bypass mode, it uses console.warn to 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.