如何测试变量是否是TypeScript中的字符串数组?像这样的:
function f(): string {
var a: string[] = ["A", "B", "C"];
if (typeof a === "string[]") {
return "Yes"
}
else {
// returns no as it's 'object'
return "No"
}
};
TypeScript.io此处:http://typescript.io/k0ZiJzso0Qg/2
编辑:我已更新文本以要求对字符串[]进行测试。这只是在前面的代码示例中。
以下是迄今为止最简明的解决方案:
注意,^{} 将返回空数组的} 添加到condition子句中:
true
。如果需要返回空数组的false
,则应将^{TypeScript中没有任何运行时类型信息(也不会有,请参见TypeScript Design Goals > Non goals,5),因此无法获取空数组的类型。对于非空数组,您只能逐个检查其项的类型。
另一个选项是Array.isArray()
在一般情况下,您不能测试
string[]
,但是可以很容易地测试Array
,就像在JavaScript中一样https://stackoverflow.com/a/767492/390330如果您特别需要
string
数组,可以执行以下操作:相关问题 更多 >
编程相关推荐