When dealing with an array of union, checking the typeof value can be done this way:
//case 1
function something1(a1: Array<number | string | boolean>)
{
for (const v of a1)
if (typeof v === "number")
v; //v is number
else if (typeof v === "boolean")
v; //v is boolean
else
v; //v is string
}
A similar approach can be taken with a union of arrays:
//case 2
function something2(a1: Array<number> | Array<string> | Array<boolean>)
{
for (const v of a1)
if (typeof v === "number")
v; //v is number
else if (typeof v === "boolean")
v; //v is boolean
else
v; //v is string
}
However, the goal is to avoid type checking inside the loop:
//case 3
function something3(a1: Array<number> | Array<string> | Array<boolean>)
{
if (a1.length === 0)
return;
if (typeof a1[0] === "number")
a1; //should be number[]!! but it is number[] | string[] | boolean[]
if (typeof a1[0] === "boolean")
a1; //should be boolean[]!! but it is number[] | string[] | boolean[]
if (typeof a1[0] === "string")
a1; //should be string[]!! but it is number[] | string[] | boolean[]
}
However, a1 is not recognized as number[], string[], or boolean[].
It would make sense since all items in the array are of the same type. Is there a way to achieve this?
The TypeScript version being used is beta 2.0.