Skip to main content

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]checkmark true
[]checkmark true
'hello'cross false
{ length: 3 }cross false
new Set([1, 2])cross 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;
}