isArray
The isArray utility is a type guard that checks if a given value is an array. It provides reliable detection across different execution environments.
Implementation
View Source Code
ts
/**
* Determines if the passed value is an array.
*
* @example
* ```ts
* isArray([1, 2, 3]) // true
* isArray(1, 2, 3) // false
* ```
*
* @param arg - The argument to be checked.
*
* @returns `true` if the value is an array, else `false`.
*/
export function isArray(arg: unknown): arg is Array<unknown> {
return Array.isArray(arg);
}
export const IS_ARRAY_ERROR_MSG = 'Expected an array';Features
- Isomorphic: Works in both Browser and Node.js.
- Type Guard: Automatically narrows the type of the checked value to
any[]orunknown[]within conditional blocks. - Reliable: Correctly identifies arrays even when they originate from different iframes or windows.
API
ts
function isArray(value: unknown): value is any[];Parameters
value: The value to check.
Returns
trueif the value is an array; otherwise,false.
Examples
Basic Usage
ts
import { isArray } from '@vielzeug/toolkit';
isArray([1, 2, 3]); // true
isArray('hello'); // false
isArray({}); // falseType Narrowing
ts
import { isArray } from '@vielzeug/toolkit';
function process(data: unknown) {
if (isArray(data)) {
// data is now typed as any[]
return data.length;
}
return 0;
}Implementation Notes
- Internally uses the native
Array.isArray()method. - Throws nothing; safely handles
null,undefined, and all other primitive or object types.