如果我有联合数组,我可以这样检查typeof值:
//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
}
如果我有数组联合,我可以这样做:
//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
}
但我想避免检查内部循环类型:
//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[]
}
但a1未被识别为number []或string []或boolean [] 但这是有道理的。由于数组中的所有项都是相同的类型。是否有可能实现这一目标?
我正在使用TypeScript beta 2.0。
答案 0 :(得分:3)
使用type guards:
function something3(a1: Array<number> | Array<string> | Array<boolean>) {
if (a1.length === 0)
return;
if (isArrayOfNumbers(a1))
a1[0].toExponential();
if (isArrayOfBooleans(a1))
a1[0].valueOf();
if (isArrayOfStrings(a1))
a1[0].indexOf('abc');
}
function isArrayOfNumbers(arr: number[] | string[] | boolean[]) : arr is number[] {
return arr.length > 0 && typeof arr[0] === 'number';
}
function isArrayOfBooleans(arr: number[] | string[] | boolean[]) : arr is boolean[] {
return arr.length > 0 && typeof arr[0] === 'boolean';
}
function isArrayOfStrings(arr: number[] | string[] | boolean[]) : arr is string[] {
return arr.length > 0 && typeof arr[0] === 'string';
}