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β
| Value | Result |
|---|---|
[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;
}
true
false