Skip to content
VersionSize

assertParams

The assertParams utility ensures that specific keys are present and non-empty in a given object. It is designed for validating function arguments or API payloads, providing clear error messages and TypeScript type narrowing.

Implementation

View Source Code
ts
import { assert } from './assert';

/**
 * Asserts that the specified keys are present in the params object and are not empty strings.
 *
 * @example
 * ```ts
 * const params = { id: '123', name: '' };
 * assertParams(params, ['id']); // Does nothing
 * assertParams(params, ['id', 'name'], 'UserUpdate'); // Throws: Missing required parameter: "name" in "UserUpdate"
 * ```
 *
 * @param params - The object containing the parameters to check.
 * @param keys - An array of keys that must be present and non-empty in the params object.
 * @param [name] - An optional name for the context of the assertion (e.g., function name).
 * @param [options] - Assertion options.
 * @param [options.type] - The error class to throw (default: `Error`).
 * @param [options.bypass] - If `true`, logs a warning instead of throwing an error.
 *
 * @throws {Error} If any of the required keys are missing or are empty strings.
 */
export function assertParams<T extends object, K extends keyof T>(
  params: T,
  keys: K[],
  name?: string,
  options: { type?: ErrorConstructor; bypass?: boolean } = {},
): asserts params is T & Required<Pick<T, K>> {
  assert(!!params, 'Missing parameters object', options);

  const missing = keys.filter((key) => params[key] === undefined || params[key] === null || params[key] === '');

  if (missing.length > 0) {
    const context = name ? ` in "${name}"` : '';
    const keysStr = missing.map((key) => `"${String(key)}"`).join(', ');
    const message = `Missing required parameter${missing.length > 1 ? 's' : ''}: ${keysStr}${context}`;

    assert(false, message, options);
  }
}

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Bulk Validation: Check multiple required keys in a single call.
  • Smart Emptiness Check: Considers null, undefined, and empty strings ('') as missing values.
  • Type Narrowing: Uses TypeScript's asserts signature to guarantee property existence in subsequent code.
  • Contextual Errors: Include the function or operation name in error messages for better traceability.

API

ts
function assertParams<T extends object, K extends keyof T>(
  params: T,
  keys: K[],
  name?: string,
  options?: {
    type?: ErrorConstructor;
    bypass?: boolean;
  },
): asserts params is T & Required<Pick<T, K>>;

Parameters

  • params: The object to validate.
  • keys: An array of property names that must be present and non-empty.
  • name: Optional. A name for the context (e.g., 'UpdateUser') to include in error messages.
  • options: Optional configuration (see assert).

Returns

  • void (Nothing) if all parameters are valid.

Examples

Validating Function Inputs

ts
import { assertParams } from '@vielzeug/toolkit';

interface User {
  id?: string;
  name?: string;
}

function saveUser(user: User) {
  // Narrow type to ensure id and name exist
  assertParams(user, ['id', 'name'], 'saveUser');

  // No need for optional chaining here
  console.log(user.id.toUpperCase());
}

With Custom Error Types

ts
import { assertParams } from '@vielzeug/toolkit';

const config = { host: 'localhost' };

// Throws TypeError if 'port' is missing
assertParams(config, ['port'], 'ConfigLoader', { type: TypeError });

Implementation Notes

  • Internally leverages the assert utility.
  • Generates descriptive error messages like: Missing required parameter: "port" in "ConfigLoader".
  • If multiple parameters are missing, it lists all of them in the error.

See Also

  • assert: The underlying generic assertion helper.
  • isEmpty: Check if a value is considered empty.
  • isDefined: Check if a value is neither null nor undefined.