Last updated: Feb 28, 2024
Reading timeยท2 min
To check if a value is an array of a specific type in TypeScript:
Array.isArray()
method to check if the value is an array.const arr: string[] = ['bobby', 'hadz', 'com']; 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.
console.log(Array.isArray([])); // ๐๏ธ true console.log(Array.isArray({})); // ๐๏ธ false console.log(Array.isArray('bobbyhadz.com')); // ๐๏ธ false const arr = ['bobby', 'hadz', 'com']; if (Array.isArray(arr)) { // ๐๏ธ this runs console.log('The value is an array'); } else { console.log('The value is not an array'); }
The Array.isArray()
method returns true
if the supplied value is an array
and false
otherwise.
I've also written an article on how to get the type of the array elements from an array type.
If you need to check if the value is an array of a specific type, you have to iterate over the array's elements and check if each element is of the specified type.
const arr: string[] = ['bobby', 'hadz', 'com']; if (Array.isArray(arr)) { const isStringArray = arr.length > 0 && arr.every((value) => { return typeof value === 'string'; }); console.log(isStringArray); // ๐๏ธ true }
The Array.every() method checks if all elements in the array pass the test implemented by the callback function.
The method returns true
if all elements pass the test and false
otherwise.
every()
method short-circuits and returns false
.If the condition is met for all array elements, the every
method returns
true
.
Notice that the first thing we did was check if the array is not empty.
const arr: string[] = ['bobby', 'hadz', 'com']; if (Array.isArray(arr)) { const isStringArray = arr.length > 0 && arr.every((value) => { return typeof value === 'string'; }); console.log(isStringArray); // ๐๏ธ true }
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 also return true
.
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.
If you need to check the type of a variable in TS, click on the link and follow the instructions.
I've also written an article on how to check if an array contains a value in TS.