Aller au contenu principal

isArray()

isArray<T>(value): value is T[]

Checks if a value is an array.


Type Parameters

T: T

The expected element type of the array.


Parameters

value: unknown

The value to check.


Returns: value is T[]

true if the value is an array, false otherwise.


Since

2.0.0


Example

isArray([1, 2, 3]); // => true
isArray('hello'); // => false

// Use instead
Array.isArray([1, 2, 3]); // => true

How it works?

Type guard that checks if a value is an array.

Type Narrowing

Common Checks

ValueResult
[1, 2, 3] true
[] true
'hello' false
{ length: 3 } false
new Set([1, 2]) false

Use Cases

Validate list structures 📌

Ensure a value is an array before iterating or mapping. Essential for processing API responses that might return single objects or arrays.

if (isArray(data)) {
data.forEach(item => process(item));
}

Normalize API responses 📌

Handle endpoints that return either a single item or an array. Essential for APIs with inconsistent response formats.

const users = isArray(response.data) 
? response.data
: [response.data];

// Now always an array
users.forEach(user => processUser(user));

Type narrowing in conditionals

Safely access array methods after type check.

function getFirst<T>(value: T | T[]): T | undefined {
if (isArray(value)) {
return value[0]; // TypeScript knows it's T[]
}
return value;
}