在 TypeScript 中测试字符串类型的数组 [英] Test for array of string type in TypeScript
问题描述
如何在 TypeScript 中测试变量是否为字符串数组?像这样:
How can I test if a variable is an array of string in TypeScript? Something like this:
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
TypeScript.io here: http://typescript.io/k0ZiJzso0Qg/2
我已更新文本以要求对字符串 [] 进行测试.这仅在之前的代码示例中.
I've updated the text to ask for a test for string[]. This was only in the code example previously.
推荐答案
在一般情况下你不能测试 string[]
但你可以很容易地测试 Array
与 JavaScript https://stackoverflow.com/a/767492/390330 相同(我更喜欢 Array.isArray(value)
).
You cannot test for string[]
in the general case but you can test for Array
quite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330 (I prefer Array.isArray(value)
).
如果您特别想要 string
数组,您可以执行以下操作:
If you specifically want for string
array you can do something like:
if (Array.isArray(value)) {
var somethingIsNotString = false;
value.forEach(function(item){
if(typeof item !== 'string'){
somethingIsNotString = true;
}
})
if(!somethingIsNotString && value.length > 0){
console.log('string[]!');
}
}
这篇关于在 TypeScript 中测试字符串类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!