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

Array Validation from unknown Sources

Use Array.isArray and type predicates to safely validate and narrow arrays of unknown elements.

Array Validation from unknown Sources

What you'll learn: How to safely validate and narrow arrays when you receive data typed as unknown, ensuring both that you have an array and that its elements match expected types.

The Array Problem with unknown

You've learned to narrow unknown values to objects, primitives, and even check for arrays with Array.isArray. But there's a gap: even after confirming something is an array, TypeScript still types it as unknown[] — an array of unknown elements. You can't safely use those elements without further validation.

When receiving data from external sources (APIs, file uploads, user input), you need a two-step process: verify it's an array, then validate what's inside.

Using Array.isArray with Type Predicates

Array.isArray narrows unknown to unknown[], but you need a type predicate to narrow further to a specific array type:

function isStringArray(value: unknown): value is string[] {
  return Array.isArray(value) && value.every(item => typeof item === 'string');
}

function processData(data: unknown) {
  if (isStringArray(data)) {
    // data is now string[]
    data.forEach(str => console.log(str.toUpperCase()));
  }
}

The predicate combines Array.isArray with every() to check each element. Only if both conditions pass does TypeScript narrow to string[].

Validating Complex Array Elements

For arrays of objects, nest your validation logic:

interface User {
  name: string;
  age: number;
}

function isUser(value: unknown): value is User {
  return typeof value === 'object' && value !== null &&
         'name' in value && typeof (value as any).name === 'string' &&
         'age' in value && typeof (value as any).age === 'number';
}

function isUserArray(value: unknown): value is User[] {
  return Array.isArray(value) && value.every(isUser);
}

By composing predicates, you build type-safe validation for nested structures.

Practical Pattern

This pattern is essential for API responses:

function validateApiResponse(response: unknown): User[] {
  if (!isUserArray(response)) {
    throw new Error('Invalid user data received');
  }
  return response; // Type-safe User[]
}

Key Takeaway: Combine Array.isArray with type predicates and every() to validate both array structure and element types, safely narrowing unknown to fully-typed arrays.