Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check the type of values in an array

I have a value that has the type string[] | object[] and depending of the type of the values in the array I want to do different things with it. Is there a way to check the types of the values in the array?

I have tried checking the type of the first item in the array, but TypeScript doesn’t recognise that, so it still thinks it can be a string[] | object[].
I also tried using every and check the type of every value but TypeScript doesn’t allow the use of every or filter on string[] | object[]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since your array is defined as string[] | object[], then it makes sense to write a type predicate to find out what type it ends up being:

function isStringArr(a_arr: string[] | object[]): a_arr is string[] {
    return !a_arr.some(a_item => typeof a_item !== 'string');
}

This is how you would use it:

if(isStringArr(arr)){
    console.log(arr); // string[]
}

Checking the type in a for or forEach loop on every element is also possible, but since your array is either string[] OR object[] this doesn’t make a whole lot of sense to do.

Playground with a few examples

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading