How to Check If Object is an Array in TypeScript

To check if an Object is an Array in TypeScript, use the “Array.isArray()” method. The isArray() method returns true if the passed value is an array and false otherwise.

function isArray(obj: any): obj is Array<any> {
  return Array.isArray(obj);
}

const testObj = { key: "value" };
const testArray = [1, 2, 3];

console.log(isArray(testObj));
console.log(isArray(testArray));

Output

Check If Object is an Array in TypeScript

In the above example, the isArray() method uses a type predicate obj is Array<any> to suggest that its result can be used to refine the obj type in situations where isArray returns true. This is particularly helpful when working with TypeScript’s type-narrowing feature.

Checking if a value is an array of a specific type

Using Type Guards

A type guard is a runtime check that guarantees the type in a specific scope. You can use a user-defined type guard to check if a value is an array of a particular type.

function isArrayOfNumbers(value: any): value is number[] {
  return Array.isArray(value) && value.every(item => typeof item === 'number');
}

const arr1: any = [1, 2, 3];
const arr2: any = [1, 'two', 3];

if (isArrayOfNumbers(arr1)) {
  console.log('arr1 is an array of numbers');
} else {
  console.log('arr1 is not an array of numbers');
}

if (isArrayOfNumbers(arr2)) {
  console.log('arr2 is an array of numbers');
} else {
  console.log('arr2 is not an array of numbers');
}

Output

Checking if a value is an array of a specific type in TypeScript

Using Generics

If you want a more generic solution that can check for arrays of any type, you can use generics:

function isArrayOf<T>(value: any, typeCheck: (item: any) => item is T): value is T[] {
  return Array.isArray(value) && value.every(typeCheck);
}

function isNumber(value: any): value is number {
  return typeof value === 'number';
}

const arr1: any = [1, 2, 3];
const arr2: any = [1, 'two', 3];

if (isArrayOf(arr1, isNumber)) {
  console.log('arr1 is an array of numbers');
} else {
  console.log('arr1 is not an array of numbers');
}

if (isArrayOf(arr2, isNumber)) {
  console.log('arr2 is an array of numbers');
} else {
  console.log('arr2 is not an array of numbers');
}

Output

Using Generics

Here, the isArrayOf() function is generic and takes in a type-checking function as its second argument. This allows you to reuse the function to check for arrays of any type by providing the appropriate type-checking function.