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