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[]
>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