UNPKG

@rzl-zone/utils-js

Version:

A modern, lightweight set of JavaScript utility functions with TypeScript support for everyday development, crafted to enhance code readability and maintainability.

827 lines (818 loc) 44.8 kB
/*! * ==================================================== * Rzl Utils-JS. * ---------------------------------------------------- * Version: 3.11.0. * Author: Rizalvin Dwiky. * Repository: https://github.com/rzl-zone/utils-js. * ==================================================== */ import { Prettify, PickStrict } from '@rzl-zone/ts-types-plus'; import { G as GetPreciseTypeOptions, I as IsNumberOptions, a as IsPlainObjectResult } from '../isPlainObject-0p3VveWr.js'; /** ------------------------------------------------------- * * ***Shape of the object passed to custom error message functions.*** * ------------------------------------------------------- * **This type describes the parameters received when `options.message` * is defined as a function in {@link OptionsAssertIs | `OptionsAssertIs`}.** * - **Parameter:** * - `currentType` ➔ the actual detected runtime type of the value. * - `validType` ➔ the required/expected type name that the value must match. * @example * ```ts * const options: OptionsAssertIs = { * message: ({ currentType, validType }) => { * return `Expected ${validType} but got ${currentType}`; * }; * }; * ``` */ type OptionsMessageFunctionAssertIs = { /** --------------------------------------------------------------------------- * * ***The actual runtime type of the value being checked.*** * --------------------------------------------------------------------------- * - ***Example:*** * - `"number"`, `"big-int"`, `"plain-object"`, (depends `formatCase` options). */ currentType: string; /** --------------------------------------------------------------------------- * * ***The required/expected type that the value must conform to.*** * --------------------------------------------------------------------------- * - ***Example:*** * - `"boolean"`, `"string"`, `"big-int"`, `"plain-object"`, (will force format to `kebab-case`). */ validType: string; }; /** ------------------------------------------------------- * * ***Custom error-message type for assertions option {@link OptionsAssertIs | `OptionsAssertIs`}.*** * ------------------------------------------------------- * - ***Accepts:*** * - A static string message. * - A function receiving `{ currentType, validType }` and returning a string. */ type OptionsMessageAssertIs = string | (({ currentType, validType }: OptionsMessageFunctionAssertIs) => string); /** --------------------------------------------------------------------------- * * ***Base options for `assertIs*` functions.*** * --------------------------------------------------------------------------- */ type OptionsAssertIs = Prettify<{ /** ------------------------------------------------------- * * ***Custom error message for assertion failures.*** * ------------------------------------------------------- * **This option allows overriding the **default error message** when a value * does not match the required type.** * - If a **string** is provided: * - Must be non-empty after trimming. * - Will be used directly as the error message. * - If a **function** is provided: * - Receives an object containing: * - `currentType` ➔ the detected runtime type of the value (depends `formatCase` options, e.g., `"number"`). * - `validType` ➔ the expected type name (with format `kebab-case`, e.g., `"boolean"`, `"big-int"`, `"plain-object"`). * - **Must** return a **string**: * - **If** the **returned string is** `empty` or `whitespace`, * the **default message** will be used instead. * @example * ```ts * // Static message * { message: "Must be a boolean!" } * * // Dynamic message * { * message: ({ currentType, validType }) => { * return `Expected ${validType} but got ${currentType}`; * }; * } * ``` */ message?: OptionsMessageAssertIs; /** ------------------------------------------------------- * * ***Custom error type for assertion failures.*** * ------------------------------------------------------- * **This option allows overriding the default error type** that will be thrown * when a value does not match the required type. * * - **Behavior:** * - Must be one of the standard JavaScript built-in error types: * `"Error" | "EvalError" | "RangeError" | "ReferenceError" | "SyntaxError" | "TypeError" | "URIError"` * - **Default:** `"TypeError"` if not provided or if an invalid value is passed. * - The assertion function will **always throw a valid built-in error**, ensuring * fallback to `TypeError` in case of an unknown or incorrect type. * @example * ```ts * // Valid: Throw a RangeError instead of TypeError * { errorType: "RangeError" } * * // Valid: Throw a ReferenceError * { errorType: "ReferenceError" } * * // Invalid value ➔ fallback to TypeError * { errorType: "SomeUnknownError" as ErrorType } * ``` */ errorType?: ErrorType; } & PickStrict<GetPreciseTypeOptions, "formatCase" | "useAcronyms">, { recursive: true; }>; type ErrorType = "Error" | "EvalError" | "RangeError" | "ReferenceError" | "SyntaxError" | "TypeError" | "URIError"; /** ------------------------------------------------------- * * ***Type guard assertion: `assertIsBoolean`.*** * ------------------------------------------------------- * **This function is an **assertion function**.** * - **Behavior:** * - Validates that the given `value` is a **boolean**. * - After it returns successfully, TypeScript narrows the type of `value` to `boolean`. * - ✅ If `value` is a `boolean` ➔ execution continues normally. * - ❌ If `value` is not a `boolean` ➔ throws a built-in error with either: * - A custom error message (`options.message`), or * - A default message including the actual type. * - **⚠️ Error type selection (`options.errorType`):** * - You can override the type of error thrown when validation fails. * - Must be one of the standard JavaScript built-in errors: * - [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | * [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | * [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | * [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | * [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | * [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) * - **Default:** `"TypeError"` if not provided or invalid. * @param {*} value - ***The value to validate.*** * @param {OptionsAssertIs} [options] * ***Optional configuration:*** * - `message`: A custom error message (`string` or `function`). * - `errorType`: A custom built-in JavaScript error type to throw. * - `formatCase`: Controls how detected type names are formatted case in error messages. * - `useAcronyms`: Control uppercase preservation of recognized acronyms during formatting. * @returns {boolean} Narrows `value` to `boolean` if no error is thrown. * @throws [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) if the value is not a boolean. * @example * ```ts * // ✅ Simple usage * assertIsBoolean(true); * // No error, value is boolean * * // ❌ Throws TypeError (default behavior) * // Case 1: Invalid input type — received a string instead of a boolean * assertIsBoolean("hello"); * // ➔ TypeError: "Parameter input (`value`) must be of type `boolean`, but received: `number`." * * // Case 2: The new Boolean() is a Boolean object (constructor), not a primitive boolean * assertIsBoolean(new Boolean(true)); * // ➔ TypeError: "Parameter input (`value`) must be of type `boolean`, but received: `boolean-constructor`." * * // ❌ Throws a TypeError with a custom string static message * assertIsBoolean(42, { message: "Must be boolean!" }); * // ➔ TypeError: "Must be boolean!" * * // ❌ Throws RangeError (custom error type) * assertIsBoolean(42, { errorType: "RangeError" }); * // ➔ RangeError: "Parameter input (`value`) must be of type `boolean`, but received: `number`." * * // ❌ Throws a TypeError with a custom message function and formatCase * assertIsBoolean(/regex/, { * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * formatCase: "toPascalCaseSpace" * }); * // ➔ TypeError: "Expected boolean but got (Reg Exp)." * * // ❌ Throws a TypeError with a custom useAcronyms option * // Case 1: * assertIsBoolean(new URL("https://example.com"),{ * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected boolean but got (url)." * assertIsBoolean(new URL("https://example.com"), { * useAcronyms: true, * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected boolean but got (URL)." * * // Case 2: * assertIsBoolean(new URLSearchParams, { * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected boolean but got (UrlSearchParams)." * assertIsBoolean(new URLSearchParams, { * useAcronyms: true, * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected boolean but got (URLSearchParams)." * ``` * ------------------------------------------------------- ****Real-world usage example***: * ```ts * const mixedValue: string | boolean | number | undefined = getUserInput(); * * // Runtime assertion: throws if `mixedValue` is not a `boolean` * assertIsBoolean(mixedValue, { * errorType: "RangeError", * message: "Must be boolean!" * }); * * // ✅ If no error thrown, TypeScript narrows `mixedValue` to `boolean` here * const result: boolean = mixedValue; // ➔ Safe type assignment * ``` */ declare const assertIsBoolean: (value: unknown, options?: OptionsAssertIs) => asserts value is boolean; /** ------------------------------------------------------- * * ***Type guard assertion: `assertIsBigInt`.*** * ------------------------------------------------------- * **This function is an **assertion function**.** * - **Behavior:** * - Validates that the given `value` is a **bigint**. * - After it returns successfully, TypeScript narrows the type of `value` to `bigint`. * - ✅ If `value` is a `bigint` ➔ execution continues normally. * - ❌ If `value` is not a `bigint` ➔ throws a built-in error with either: * - A custom error message (`options.message`), or * - A default message including the actual type. * - **ℹ️ Note:** * - A `bigint` refers strictly to the JavaScript `bigint` primitive type (e.g., `123n`, `0n`, `-999999999999999999999n`). * - This excludes `BigInt` objects created with `Object(BigInt(123))`. * - **⚠️ Error type selection (`options.errorType`):** * - You can override the type of error thrown when validation fails. * - Must be one of the standard JavaScript built-in errors: * - [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | * [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | * [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | * [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | * [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | * [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) * - **Default:** `"TypeError"` if not provided or invalid. * @param {*} value - ***The value to validate.*** * @param {OptionsAssertIs} [options] * ***Optional configuration:*** * - `message`: A custom error message (`string` or `function`). * - `errorType`: Built-in JavaScript error type to throw on failure (default `"TypeError"`). * - `formatCase`: Controls how detected type names are formatted case in error messages. * - `useAcronyms`: Control uppercase preservation of recognized acronyms during formatting. * @returns {boolean} Narrows `value` to `bigint` if no error is thrown. * @throws [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) if the value is not a bigint. * @example * ```ts * // ✅ Simple usage * assertIsBigInt(123n); * // No error, value is bigint * * // ❌ Throws TypeError (default behavior) * assertIsBigInt(42); * // ➔ TypeError: "Parameter input (`value`) must be of type `bigint`, but received: `number`." * * // ❌ Throws a TypeError with a custom string static message * assertIsBigInt("123", { message: "Must be a bigint!" }); * // ➔ TypeError: "Must be a bigint!" * * // ❌ Throws custom error type (e.g., RangeError) * assertIsBigInt(async function () {}, { errorType: "RangeError" }); * // ➔ RangeError: "Parameter input (`value`) must be of type `bigint`, but received: `async-function`." * * // ❌ Throws a TypeError with a custom message function and formatCase * assertIsBigInt(/regex/, { * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * formatCase: "toPascalCaseSpace" * }); * // ➔ TypeError: "Expected bigint but got (Reg Exp)." * * // ❌ Throws a TypeError with a custom useAcronyms option * // Case 1: * assertIsBigInt(new URL("https://example.com"),{ * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected bigint but got (url)." * assertIsBigInt(new URL("https://example.com"), { * useAcronyms: true, * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected bigint but got (URL)." * * // Case 2: * assertIsBigInt(new URLSearchParams, { * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected bigint but got (UrlSearchParams)." * assertIsBigInt(new URLSearchParams, { * useAcronyms: true, * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected bigint but got (URLSearchParams)." * ``` * ------------------------------------------------------- ****Real-world usage example***: * ```ts * const mixedValue: string | bigint | undefined = getUserInput(); * * // Runtime assertion: throws if `mixedValue` is not a `bigint` * assertIsBigInt(mixedValue, { * errorType: "RangeError", * message: "Must be bigint!" * }); * * // ✅ If no error thrown, TypeScript narrows `mixedValue` to `bigint` here * const result: bigint = mixedValue; // ➔ Safe type assignment * console.log(result + 100n); // ➔ Safe to operation * ``` */ declare const assertIsBigInt: (value: unknown, options?: OptionsAssertIs) => asserts value is bigint; type OptionsAssertIsNumber = OptionsAssertIs & IsNumberOptions; /** ------------------------------------------------------- * * ***Type guard assertion: `assertIsNumber`.*** * ------------------------------------------------------- * **This function is an **assertion function**.** * - **Behavior:** * - Validates that the given `value` is a **number**. * - After it returns successfully, TypeScript narrows the type of `value` to `number`. * - ✅ If `value` is a `number` ➔ execution continues normally. * - ❌ If `value` is not a `number` ➔ throws a built-in error with either: * - A custom error message (`options.message`), or * - A default message including the actual type. * - **ℹ️ Note:** * - A `number` refers strictly to the JavaScript `number` primitive type (e.g., `42`, `3.14`, `-1`, `0`). * - This excludes `Number` objects created with `new Number(123)`. * - By default, `NaN` is **not considered** valid, you can allow it with `{ includeNaN: true }`. * - **⚠️ Error type selection (`options.errorType`):** * - You can override the type of error thrown when validation fails. * - Must be one of the standard JavaScript built-in errors: * - [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | * [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | * [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | * [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | * [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | * [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) * - **Default:** `"TypeError"` if not provided or invalid. * @param {*} value - ***The value to validate.*** * @param {OptionsAssertIsNumber} [options] * ***Optional configuration:*** * - `message`: A custom error message (`string` or `function`). * - `errorType`: Built-in JavaScript error type to throw on failure (default `"TypeError"`). * - `formatCase`: Controls how detected type names are formatted case in error messages. * - `useAcronyms`: Control uppercase preservation of recognized acronyms during formatting. * - `includeNaN`: Whether to treat `NaN` as valid. * @returns {boolean} Narrows `value` to `number` if no error is thrown. * @throws [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) if the value is not a number (or is `NaN` when `includeNaN` is `false`). * @example * ```ts * // ✅ Simple usage * assertIsNumber(123); * assertIsNumber(NaN, { includeNaN: true }); * // No error, value is number * * // ❌ Throws TypeError (default behavior) * // Case 1: Invalid input type — received a string instead of a number * assertIsNumber("42"); * // ➔ TypeError: "Parameter input (`value`) must be of type `number`, but received: `string`." * * // Case 2: Default option includeNaN is false * assertIsNumber(NaN); * // ➔ TypeError: "Parameter input (`value`) must be of type `number`, but received: `NaN`." * * // Case 3: The new Number() is a Number object (constructor), not a primitive number * assertIsNumber(new Number("123")); * // ➔ TypeError: "Parameter input (`value`) must be of type `number`, but received: `number-constructor`." * * // ❌ Throws custom error type (e.g., RangeError) * assertIsNumber(async function () {}, { errorType: "RangeError" }); * // ➔ RangeError: "Parameter input (`value`) must be of type `number`, but received: `async-function`." * * // ❌ Throws a TypeError with a custom string static message * assertIsNumber("123", { message: "Must be a number!" }); * // ➔ TypeError: "Must be a number!" * * // ❌ Throws a TypeError with a custom message function and formatCase * assertIsNumber(/regex/, { * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * formatCase: "toPascalCaseSpace" * }); * // ➔ TypeError: "Expected number but got (Reg Exp)." * * // ❌ Throws a TypeError with a custom useAcronyms option * // Case 1: * assertIsNumber(new URL("https://example.com"),{ * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected number but got (url)." * assertIsNumber(new URL("https://example.com"), { * useAcronyms: true, * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected number but got (URL)." * * // Case 2: * assertIsNumber(new URLSearchParams, { * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected number but got (UrlSearchParams)." * assertIsNumber(new URLSearchParams, { * useAcronyms: true, * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected number but got (URLSearchParams)." * ``` * ------------------------------------------------------- ****Real-world usage example***: * ```ts * const mixedValue: string | number | undefined = getUserInput(); * * // Runtime assertion: throws if `mixedValue` is not a `number` * assertIsNumber(mixedValue, { * errorType: "RangeError", * message: "Must be number!" * }); * * // ✅ If no error thrown, TypeScript narrows `mixedValue` to `number` here * const result: number = mixedValue; // ➔ Safe type assignment * console.log(result + 100); // ➔ Safe to operation * ``` */ declare const assertIsNumber: (value: unknown, options?: OptionsAssertIsNumber) => asserts value is number; /** ------------------------------------------------------- * * ***Type guard assertion: `assertIsArray`.*** * ------------------------------------------------------- * **This function is an **assertion function**.** * - **Behavior:** * - Validates that the given `value` is an **array**. * - After it returns successfully, TypeScript narrows the type of `value` to `array` **(generic support)**. * - ✅ If `value` is an `array` ➔ execution continues normally. * - ❌ If `value` is not an `array` ➔ throws a built-in error with either: * - A custom error message (`options.message`), or * - A default message including the actual type. * - **⚠️ Error type selection (`options.errorType`):** * - You can override the type of error thrown when validation fails. * - Must be one of the standard JavaScript built-in errors: * - [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | * [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | * [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | * [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | * [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | * [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) * - **Default:** `"TypeError"` if not provided or invalid. * @template T - The input type being asserted. * @param {*} value - ***The value to validate.*** * @param {OptionsAssertIs} [options] * ***Optional configuration:*** * - `message`: A custom error message (`string` or `function`). * - `errorType`: Built-in JavaScript error type to throw on failure (default `"TypeError"`). * - `formatCase`: Controls how detected type names are formatted case in error messages. * - `useAcronyms`: Control uppercase preservation of recognized acronyms during formatting. * @returns {boolean} Narrows `value` to an `array` **(generic support)** if no error is thrown. * @throws [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) if the value is not an array. * @example * ```ts * // ✅ Simple usage * assertIsArray([]); * assertIsArray(["123", 456]); * assertIsArray(Array.from(["abc"])); * // No error, value is array * * // ❌ 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 custom error type (e.g., RangeError) * assertIsArray(async function () {}, { errorType: "RangeError" }); * // ➔ RangeError: "Parameter input (`value`) must be of type `array`, but received: `async-function`." * * // ❌ Throws a TypeError with a custom string static message * assertIsArray("123", { message: "Must be a array!" }); * // ➔ TypeError: "Must be a array!" * * // ❌ Throws a TypeError with a custom message function and formatCase * assertIsArray(/regex/, { * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * formatCase: "toPascalCaseSpace" * }); * // ➔ TypeError: "Expected array but got (Reg Exp)." * * // ❌ Throws a TypeError with a custom useAcronyms option * // 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)." * ``` * ------------------------------------------------------- ****Real-world usage example***: * ```ts * const mixedValue: string | number[] | undefined = getUserInput(); * * // Runtime assertion: throws if `mixedValue` is not a `number[]` * assertIsArray(mixedValue, { * errorType: "RangeError", * message: "Must be array!" * }); * * // ✅ If no error thrown, TypeScript narrows `mixedValue` to `number[]` here * const result: number[] = mixedValue; // ➔ Safe type assignment * console.log(result.push(1, 2, 3)); // ➔ Safe to use array methods * ``` */ declare function assertIsArray<T extends unknown[]>(value: T, options?: OptionsAssertIs): asserts value is Extract<T, unknown[]>; declare function assertIsArray<T extends readonly unknown[]>(value: T, options?: OptionsAssertIs): asserts value is Extract<T, readonly unknown[]>; declare function assertIsArray(value: unknown, options?: OptionsAssertIs): asserts value is unknown[]; /** ------------------------------------------------------- * * ***Type guard assertion: `assertIsPlainObject`.*** * ------------------------------------------------------- * **This function is an **assertion function**.** * - **Behavior:** * - Validates that the given `value` is a **plain-object**. * - After it returns successfully, TypeScript narrows the type of `value` to `plain-object` **(generic support)**. * - ✅ If `value` is a `plain-object` ➔ execution continues normally. * - ❌ If `value` is not a `plain-object` ➔ throws a built-in error with either: * - A custom error message (`options.message`), or * - A default message including the actual type. * - **A valid `plain object` is:** * - Created by the `Object` constructor, or * - Has a `[[Prototype]]` of `null` (e.g. `Object.create(null)`). * - **✅ Returns `undefined` (valid) for:** * - Empty object literals: `{}` * - Objects with null prototype: `Object.create(null)` * - **❌ Returns `throws` for:** * - Arrays (`[]`, `new Array()`) * - Functions (regular, arrow, or class constructors) * - Built-in objects: `Date`, `RegExp`, `Error`, `Map`, `Set`, `WeakMap`, `WeakSet` * - Boxed primitives: `new String()`, `new Number()`, `new Boolean()` * - `null` or `undefined` * - Symbols * - Class instances * - **⚠️ Error type selection (`options.errorType`):** * - You can override the type of error thrown when validation fails. * - Must be one of the standard JavaScript built-in errors: * - [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | * [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | * [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | * [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | * [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | * [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) * - **Default:** `"TypeError"` if not provided or invalid. * @template T - The input type being asserted. * @param {*} value - ***The value to validate.*** * @param {OptionsAssertIs} [options] * ***Optional configuration:*** * - `message`: A custom error message (`string` or `function`). * - `errorType`: Built-in JavaScript error type to throw on failure (default `"TypeError"`). * - `formatCase`: Controls how detected type names are formatted case in error messages. * - `useAcronyms`: Control uppercase preservation of recognized acronyms during formatting. * @returns {boolean} Narrows `value` to a `plain-object` **(generic support)** if no error is thrown. * @throws [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) if `value` is not a plain-object. * @example * ```ts * // ✅ Simple usage * assertIsPlainObject({ a: 1, b: 2 }); * // No error, value is plain-object * * // ❌ Throws TypeError (default behavior) * // Case 1: Invalid input type — received a string instead of a plain-object * assertIsPlainObject("42"); * // ➔ TypeError: "Parameter input (`value`) must be of type `plain-object`, but received: `string`." * * // ❌ Throws custom error type (e.g., RangeError) * assertIsPlainObject(async function () {}, { errorType: "RangeError" }); * // ➔ RangeError: "Parameter input (`value`) must be of type `plain-object`, but received: `async-function`." * * // ❌ Throws a TypeError with a custom string static message * assertIsPlainObject("123", { message: "Must be a plain-object!" }); * // ➔ TypeError: "Must be a plain-object!" * * // ❌ Throws a TypeError with a custom message function and formatCase * assertIsPlainObject(/regex/, { * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * formatCase: "toPascalCaseSpace" * }); * // ➔ TypeError: "Expected plain-object but got (Reg Exp)." * * // ❌ Throws a TypeError with a custom useAcronyms option * // Case 1: * assertIsPlainObject(new URL("https://example.com"),{ * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected plain-object but got (url)." * assertIsPlainObject(new URL("https://example.com"), { * useAcronyms: true, * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected plain-object but got (URL)." * * // Case 2: * assertIsPlainObject(new URLSearchParams, { * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected plain-object but got (UrlSearchParams)." * assertIsPlainObject(new URLSearchParams, { * useAcronyms: true, * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected plain-object but got (URLSearchParams)." * ``` * ------------------------------------------------------- ****Real-world usage with generic narrowing***: * ```ts * type User = { name: string; email: string }; * const mixedValue: string | User | boolean | number | undefined = getUserInput(); * * // Runtime assertion: throws if `mixedValue` is not a `plain-object` * assertIsPlainObject(mixedValue, { * errorType: "RangeError", * message: "Must be plain object!" * }); * * // ✅ If no error thrown, TypeScript narrows `mixedValue` to `User` here * const user: User = mixedValue; // ➔ Safe type assignment * console.log(user.email); // ➔ Safe to access object properties * ``` */ declare function assertIsPlainObject<T>(value: T, options?: OptionsAssertIs): asserts value is IsPlainObjectResult<T>; /** ------------------------------------------------------- * * ***Type guard assertion: `assertIsString`.*** * ------------------------------------------------------- * **This function is an **assertion function**.** * - **Behavior:** * - Validates that the given `value` is a **primitive-string**. * - After it returns successfully, TypeScript narrows the type of `value` to `primitive-string`. * - ✅ If `value` is a `primitive-string` ➔ execution continues normally. * - ❌ If `value` is not a `primitive-string` ➔ throws a built-in error with either: * - A custom error message (`options.message`), or * - A default message including the actual type. * - **ℹ️ Note:** * - A "string" refers strictly to a JavaScript `primitive-string` type (e.g., `"hello"`, `""`, `"123"`). * - This function excludes `String` objects created with `new String()`. * - **⚠️ Error type selection (`options.errorType`):** * - You can override the type of error thrown when validation fails. * - Must be one of the standard JavaScript built-in errors: * - [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | * [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | * [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | * [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | * [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | * [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) * - **Default:** `"TypeError"` if not provided or invalid. * @param {*} value - ***The value to validate.*** * @param {OptionsAssertIs} [options] * ***Optional configuration:*** * - `message`: A custom error message (`string` or `function`). * - `errorType`: Built-in JavaScript error type to throw on failure (default `"TypeError"`). * - `formatCase`: Controls how detected type names are formatted case in error messages. * - `useAcronyms`: Control uppercase preservation of recognized acronyms during formatting. * @returns {boolean} Narrows `value` to `string` if no error is thrown. * @throws [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) | [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) | [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) | [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) | [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) if the value is not a primitive string. * @example * ```ts * // ✅ Simple usage * assertIsString("hello"); * // No error, value is string * * // ❌ Throws TypeError (default behavior) * // Case 1: Invalid input type — received a string instead of a string * assertIsString(42); * // ➔ TypeError: "Parameter input (`value`) must be of type `string`, but received: `number`." * * // Case 3: The new String() is a String object (constructor), not a primitive string * assertIsString(new String("abc")); * // ➔ TypeError: "Parameter input (`value`) must be of type `string`, but received: `string-constructor`." * * // ❌ Throws custom error type (e.g., RangeError) * assertIsString(async function () {}, { errorType: "RangeError" }); * // ➔ RangeError: "Parameter input (`value`) must be of type `string`, but received: `async-function`." * * // ❌ Throws a TypeError with a custom string static message * assertIsString(123, { message: "Must be a string!" }); * // ➔ TypeError: "Must be a string!" * * // ❌ Throws a TypeError with a custom message function and formatCase * assertIsString(/regex/, { * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * formatCase: "toPascalCaseSpace" * }); * // ➔ TypeError: "Expected string but got (Reg Exp)." * * // ❌ Throws a TypeError with a custom useAcronyms option * // Case 1: * assertIsString(new URL("https://example.com"),{ * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected string but got (url)." * assertIsString(new URL("https://example.com"), { * useAcronyms: true, * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected string but got (URL)." * * // Case 2: * assertIsString(new URLSearchParams, { * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected string but got (UrlSearchParams)." * assertIsString(new URLSearchParams, { * useAcronyms: true, * formatCase: "toPascalCase", * message: ({ currentType, validType }) => { * return `Expected ${validType} but got (${currentType}).` * }, * }); * // ➔ TypeError: "Expected string but got (URLSearchParams)." * ``` * ------------------------------------------------------- ****Real-world usage with generic narrowing***: * ```ts * const mixedValue: string | boolean | undefined = getUserInput(); * * // Runtime assertion: throws if `mixedValue` is not a `string` * assertIsString(mixedValue, { * errorType: "RangeError", * message: "Must be a string!" * }); * * // ✅ If no error thrown, TypeScript narrows `mixedValue` to `string` here * const result: string = mixedValue; // ➔ Safe type assignment * console.log(result.toUpperCase()); // ➔ Safe to call String.prototype methods * ``` */ declare const assertIsString: (value: unknown, options?: OptionsAssertIs) => asserts value is string; export { assertIsArray, assertIsBigInt, assertIsBoolean, assertIsNumber, assertIsPlainObject, assertIsString };