Array.isArray for Array vs Non-Array
What you'll learn: How to use Array.isArray() to safely narrow union types that contain both arrays and non-array values.
When you have a union type that includes an array alongside non-array types, TypeScript needs help figuring out which branch you're working with. The built-in JavaScript function Array.isArray() acts as a type guard that TypeScript understands, letting you safely narrow to just the array type.
Why You Need This
Sometimes your code receives a value that could be an array or something else entirely. Maybe it's a string, maybe it's an array of strings. You can't just call .map() or .length on a union without narrowing first—TypeScript won't let you access array-specific methods on potentially non-array values.
How Array.isArray Works as a Type Guard
Array.isArray() is special: TypeScript recognizes it as a narrowing mechanism. When you use it in an if statement, TypeScript automatically narrows the type inside that branch.
function processValue(value: string | string[]) {
if (Array.isArray(value)) {
// TypeScript knows: value is string[]
console.log(value.join(", "));
} else {
// TypeScript knows: value is string
console.log(value.toUpperCase());
}
}
Beyond Simple Arrays
This works with any array type in a union, including arrays of objects, numbers, or mixed-type arrays:
function handleData(data: number[] | boolean) {
if (Array.isArray(data)) {
// data is number[]
const sum = data.reduce((a, b) => a + b, 0);
} else {
// data is boolean
console.log(data ? "yes" : "no");
}
}
Key Takeaway: Use Array.isArray() as a type guard to safely narrow union types containing arrays, giving you access to array-specific methods and properties in the narrowed branch.