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

Array Element Narrowing Patterns

Techniques for narrowing unknown array elements with guards inside loops or map callbacks.

Array Element Narrowing Patterns

What you'll learn: How to safely narrow the type of individual elements when working with arrays of unknown values.

The Challenge with Unknown Arrays

When you have an array typed as unknown[], TypeScript treats every individual element as unknown. You can't just narrow the array itself—you need to narrow each element as you work with it. This comes up constantly when processing data from external sources: parsing JSON responses, handling dynamic configurations, or iterating over untyped collections.

Narrowing in Loops

The most common pattern is using type guards inside loops:

function processItems(items: unknown[]): string[] {
  const results: string[] = [];
  
  for (const item of items) {
    // item is unknown here
    if (typeof item === "string") {
      // item is string here!
      results.push(item.toUpperCase());
    }
  }
  
  return results;
}

Each iteration starts fresh—item is unknown, and you narrow it with guards like typeof, instanceof, or custom type predicates.

Narrowing in Array Method Callbacks

Array methods like map, filter, and forEach work the same way—narrow the parameter inside the callback:

const data: unknown[] = [1, "hello", 2, null, "world"];

// Filter to only strings
const strings = data.filter((item): item is string => {
  return typeof item === "string";
});
// strings is now string[]

// Map with narrowing
const doubled = data.map(item => {
  if (typeof item === "number") {
    return item * 2;
  }
  return 0; // fallback for non-numbers
});

Notice the type predicate in filter—this is crucial for TypeScript to understand that the resulting array contains only strings.

Combining Multiple Guards

For complex data, chain your checks:

function extractNames(items: unknown[]): string[] {
  return items
    .filter((item): item is { name: unknown } => {
      return typeof item === "object" && item !== null && "name" in item;
    })
    .map(item => item.name)
    .filter((name): name is string => typeof name === "string");
}

Each narrowing step progressively refines the type until you have exactly what you need.

Key Takeaway: When working with unknown[], narrow each element individually using type guards inside loops or callbacks—the array type doesn't automatically flow through to its contents.