Array Type Guards and Narrowing
What you'll learn: How to safely check whether a value is an array and narrow its type using TypeScript's built-in tools.
The Problem
When working with mixed data or union types, you often receive a value that might be an array—or might be something else entirely. TypeScript can't assume what it is until you explicitly check.
Using Array.isArray()
JavaScript's Array.isArray() is a type guard in TypeScript. When you call it, TypeScript narrows the type from a broader union down to an array:
function processValue(value: string | number[]) {
if (Array.isArray(value)) {
// TypeScript now knows value is number[]
console.log(value.length); // ✓ Safe
} else {
// TypeScript now knows value is string
console.log(value.toUpperCase()); // ✓ Safe
}
}
Think of it like a security checkpoint: Array.isArray() proves the value has an array badge, so TypeScript lets it access array-specific properties.
Filtering to Narrow Array Contents
You can also filter arrays to narrow their internal types:
const mixed: (string | number)[] = [1, "hello", 2];
const numbersOnly = mixed.filter((item): item is number => typeof item === "number");
// numbersOnly is now number[]
The : item is number syntax creates a user-defined type guard, teaching TypeScript what the filter guarantees.
When to Use This
Use array type guards whenever you're dealing with union types that include arrays, receiving unknown data, or need to prove to TypeScript that a value is definitely an array before calling methods like .map() or .filter().
Key Takeaway: Use Array.isArray() to narrow union types to arrays, and combine it with filtering methods to safely transform and narrow array contents.