UtilsJSAssertionsassertIsArray

Assertion: assertIsArray

Assert a value is strictly array — UtilsJS version 3.

Overview

The assertIsArray utility in UtilsJS is a runtime assertion function that verifies whether a given value is a array (e.g., [123, "abc", true, undefined], new Array([true, 123, "abc"])).
If the value is not array, it throws a TypeError (by default), helping enforce strict type safety both at runtime and during development.
This utility is ideal for validation logic, defensive programming, and any scenario where input integrity and reliability are critical.

Fully supports TypeScript generics, readonly arrays, and tuple types — ensuring accurate type narrowing for both mutable and immutable structures.
After a successful assertion, the inferred type of value is automatically refined, providing complete compile-time safety and seamless integration with complex generic scenarios.

Importing

import { assertIsArray } from "@rzl-zone/utils-js/assertions";
const { assertIsArray } = require("@rzl-zone/utils-js/assertions");

Syntax

assertIsArray(
  value: unknown,
  options?: OptionsAssertIs
): asserts value is unknown[]
assertIsArray(value, options?): void

Parameters

Prop

Type

Options

Optional configuration object that defines how the utility function should behave in various scenarios, allowing customization and greater control at runtime.


message

  • Description:
    Custom message or message generator function for assertion failure.
  • Required:
  • Type:
    string | ({ currentType, validType }) => string | undefined
  • Default:
    "Parameter input (`value`) must be of type `array`, but received: `xxx`."
  • Example:
    1. Static message example:

      TypeScript/JavaScript
      assertIsArray("123", {
        message: "Must be a (array)!"
      });
      // ➔ TypeError: "Must be a (array)!"
    2. Dynamic message example:

      TypeScript/JavaScript
      assertIsArray("invalid", {
        message: ({ currentType, validType }) => {
          return `Expected \`${validType}\` but got \`${currentType}\`.`;
        }
      });
      // ➔ TypeError: "Expected `array` but got `string`."
      • The function receives an object:
        TypeScript/JavaScript
        {
          // Detected runtime type, such as:
          // - "string", "boolean", "plain-object", etc.
          currentType: string;
          // Required type name (formatted according to formatCase)
          validType: string;
        };

Note

  • The message value will trimmed automatically.
  • The message fallback to the default, if:
    1. Value is not a string.
    2. Value is empty-string.
    3. Value is a function but does not return a string.

errorType

  • Description:
    The JavaScript built-in error type to throw.
  • Required:
  • Type:
    "Error" | "EvalError" | "RangeError" | "ReferenceError" | "SyntaxError" | "TypeError" | "URIError" | undefined
  • Default:
    "TypeError"
  • Example:
    TypeScript/JavaScript
    assertIsArray("123", {
      message: ({ currentType, validType }) => {
        return `Expected \`${validType}\` but got (${currentType}).`;
      },
      errorType: "RangeError",
    });
    // ➔ RangeError: "Expected `array` but got (string)."
    
    assertIsArray(1000n, {
      message: ({ currentType, validType }) => {
        return `Expected \`${validType}\` but got (${currentType}).`;
      },
      errorType: "SyntaxError",
    });
    // ➔ SyntaxError: "Expected `array` but got (bigint)."

Note

The errorType fallback to the default, if the given value is invalid.


formatCase

  • Description:
    Controls how detected type names are formatted in error messages.
  • Required:
  • Type:
    "toPascalCaseSpace" | "toPascalCase" | "toCamelCase" | "toKebabCase" | "toSnakeCase" | "toDotCase" | "slugify" | "toLowerCase" | undefined
  • Default:
    "toKebabCase"
  • Example:
    TypeScript/JavaScript
    // with default formatCase:
    assertIsArray(/regex/, {
      message: ({ currentType, validType }) => {
        return `Expected ${validType} but got (${currentType}).`;
      },
    });
    // ➔ TypeError: "Expected `array` but got (reg-exp)."
    
    // customize formatCase to camel case:
    assertIsArray(/regex/, {
      message: ({ currentType, validType }) => {
        return `Expected \`${validType}\` but got (${currentType}).`;
      },
      formatCase: "toCamelCase"
    });
    // ➔ TypeError: "Expected `array` but got (regExp)."
    
    // customize formatCase to pascal case space:
    assertIsArray(async function () {}, {
      message: ({ currentType, validType }) => {
        return `Expected \`${validType}\` but got (${currentType}).`;
      },
      formatCase: "toPascalCaseSpace"
    });
    // ➔ TypeError: "Expected `array` but got (Async Function)."

Note

  • The formatCase fallback to the default, if the given value is invalid.
  • Special type (-Infinity | Infinity | NaN) will remain unchanged even if a different formatCase is applied.

useAcronyms

  • Description:
    Control uppercase preservation of recognized acronyms during formatting.
  • Required:
  • Type:
    boolean | undefined
  • Default:
    false
  • Example:
    TypeScript/JavaScript
    // Case 1:
    assertIsArray(new URL("https://example.com"),{
      message: ({ currentType, validType }) => {
        return `Expected ${validType} but got (${currentType}).`
      }
    });
    // ➔ TypeError: "Expected array but got (url)."
    assertIsArray(new URL("https://example.com"), {
      useAcronyms: true,
      message: ({ currentType, validType }) => {
        return `Expected ${validType} but got (${currentType}).`
      }
    });
    // ➔ TypeError: "Expected array but got (URL)."
    
    // Case 2:
    assertIsArray(new URLSearchParams, {
      formatCase: "toPascalCase",
      message: ({ currentType, validType }) => {
        return `Expected ${validType} but got (${currentType}).`
      }
    });
    // ➔ TypeError: "Expected array but got (UrlSearchParams)."
    assertIsArray(new URLSearchParams, {
      useAcronyms: true,
      formatCase: "toPascalCase",
      message: ({ currentType, validType }) => {
        return `Expected ${validType} but got (${currentType}).`
      }
    });
    // ➔ TypeError: "Expected array but got (URLSearchParams)."


Note

The useAcronyms fallback to the default, if the given value is invalid.
This option affects formatting output only, not the underlying type detection, acronym preservation is applied after detecting and formatting the base type name.

Returns

This function does not return a value.
It asserts the type of value and throws an error if the type check fails.

Throws

Throws a built-in JavaScript error when the provided value does not match the array type.

Supported error types:

  • TypeError (default)
  • Error
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • URIError

Examples

TypeScript/JavaScript
import { assertIsArray } from "@rzl-zone/utils-js/assertions";

// ✅ Works as expected
assertIsArray([123, "456"]);
assertIsArray(new Array(123, "456"));

// ❌ Throws TypeError (default behavior)
// Case 1: Invalid input type — received a string instead of a array
assertIsArray("42");
// ➔ TypeError: "Parameter input (`value`) must be of type `array`, but received: `string`."

// ❌ Throws RangeError (custom error type)
assertIsArray(new String("[]"), { errorType: "RangeError" });
// ➔ RangeError: "Parameter input (`value`) must be of type `array`, but received: `string-constructor`."

// ❌ Throws a TypeError with a custom message function and formatCase
assertIsArray(async function () {}, {
  message: ({ currentType, validType }) => {
    return `Expected ${validType} but got (${currentType}).`;
  },
  formatCase: "toPascalCaseSpace"
});
// ➔ TypeError: "Expected array but got (Async Function)."

// ❌ Throws a TypeError with a custom useAcronyms option
// Case 1: With default formatCase option
assertIsArray(new URL("https://example.com"),{
  message: ({ currentType, validType }) => {
    return `Expected ${validType} but got (${currentType}).`
  },
});
// ➔ TypeError: "Expected array but got (url)."
assertIsArray(new URL("https://example.com"), {
  useAcronyms: true,
  message: ({ currentType, validType }) => {
    return `Expected ${validType} but got (${currentType}).`
  },
});
// ➔ TypeError: "Expected array but got (URL)."

// Case 2: With custom formatCase option
assertIsArray(new URLSearchParams, {
  formatCase: "toPascalCase",
  message: ({ currentType, validType }) => {
    return `Expected ${validType} but got (${currentType}).`
  },
});
// ➔ TypeError: "Expected array but got (UrlSearchParams)."
assertIsArray(new URLSearchParams, {
  useAcronyms: true,
  formatCase: "toPascalCase",
  message: ({ currentType, validType }) => {
    return `Expected ${validType} but got (${currentType}).`
  },
});
// ➔ TypeError: "Expected array but got (URLSearchParams)."

Real-World Example

TypeScript/JavaScript
const mixedValue: string | boolean | string[] | undefined = getUserInput();

// Runtime assertion: throws if mixedValue is not a array
assertIsArray(mixedValue, {
  message: "Must be array!",
  errorType: "RangeError",
  formatCase: "toPascalCase"
});

// If no error thrown, TypeScript narrows mixedValue to array here
const result: string[] | Array<string> = mixedValue;
console.log(result.push("hello", "world")); // ➔ safe to call array method

Version Information

  • Since: v3.10.0.
  • Category: assertions.
  • Stability: Stable (Production-ready).
Made with ❤️ by @rzl-app