Course contentsShow
← TypeScript
Lesson 916 of 1,79621. The unknown TypeFree lesson

Array.isArray for Array Narrowing

How Array.isArray narrows unknown to an array type, though elements remain unknown.

Array.isArray for Array Narrowing

What you'll learn: How to use Array.isArray to narrow an unknown value down to an array type while keeping element types safe.

The Problem with unknown and Arrays

When you have an unknown value, TypeScript blocks all operations on it—including treating it as an array. Even if you suspect the value is an array, you can't access properties or use array methods without narrowing first.

function processData(data: unknown) {
  // ❌ Error: Object is of type 'unknown'
  // data.length;
  // data[0];
}

Enter Array.isArray

JavaScript's built-in Array.isArray() function checks whether a value is an array at runtime. TypeScript recognizes this as a type guard and will narrow unknown to an array type.

function processData(data: unknown) {
  if (Array.isArray(data)) {
    // ✅ TypeScript knows data is an array here
    console.log(data.length);
    data.forEach(item => {
      // item is 'unknown' though!
    });
  }
}

The Catch: Elements Remain unknown

Here's the important limitation: Array.isArray only tells TypeScript that data is some kind of array—it becomes unknown[]. The elements themselves are still unknown, because TypeScript has no way to know what's inside the array at compile time.

function handleValue(value: unknown) {
  if (Array.isArray(value)) {
    // value is now unknown[]
    for (const item of value) {
      // item is unknown—you need further narrowing!
      if (typeof item === "string") {
        console.log(item.toUpperCase());
      }
    }
  }
}

Think of it like opening a box: Array.isArray confirms you have a box of items, but you still need to inspect each item individually to know what it contains.

Key Takeaway: Array.isArray narrows unknown to unknown[], allowing array operations, but you must narrow each element separately to work with them safely.