Check if a Value is an Array (of type) in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 11, 2022

banner

Photo from Unsplash

Check if a Value is an Array (of type) in TypeScript #

To check if a value is an array of specific type in TypeScript:

  1. Use the Array.isArray() method to check if the value is an array.
  2. Iterate over the array and check if each value is of the specific type.
index.ts
const arr: string[] = ['a', 'b', 'c']; const isArray = Array.isArray(arr); // 👉️ true if (Array.isArray(arr)) { const isStringArray = arr.length > 0 && arr.every((value) => { return typeof value === 'string'; }); console.log(isStringArray); // 👉️ true }

You can use the Array.isArray method to check if a value is an array in TypeScript.

index.ts
console.log(Array.isArray([])); // 👉️ true console.log(Array.isArray({})); // 👉️ false console.log(Array.isArray('hello')); // 👉️ false

The method takes a value as a parameter and returns a boolean result - true if the value is an array and false otherwise.

If you need to check if the value is an array of specific type, you have to iterate over the array's elements and check if each element is of the specific type.

We used the Array.every() method to iterate over the array.

The function we passed to the every method gets called with each element until it returns a falsy value or iterates over the entire array.

index.ts
const arr: string[] = ['a', 'b', 'c']; if (Array.isArray(arr)) { const isStringArray = arr.length > 0 && arr.every((value) => { return typeof value === 'string'; }); console.log(isStringArray); // 👉️ true }

Notice that the first thing we did was check if the array is not empty.

Calling the every() method on an empty array will always return true, regardless of the implemented condition.

This is why we check if the array has more than 0 elements - to avoid any false positives.

If the callback function we passed to the every method returns true on all iterations, the every method will return true as well.

This is the only way to check if all of the elements in the array are of a specific type.

If you aren't fetching the array from a remote source, e.g. an API, and you're using TypeScript, you can pretty much assume that the array contains elements of the expected type, unless you used any or type assertions when working with the array.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.