Test for array of string type in 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 here: http://typescript.io/k0ZiJzso0Qg/2
Edit: I've updated the text to ask for a test for string[]. This was only in the code example previously.
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
If you specifically want for string
array you can do something like:
if (value instanceof Array) {
var somethingIsNotString = false;
value.forEach(function(item){
if(typeof item !== 'string'){
somethingIsNotString = true;
}
})
if(!somethingIsNotString){
console.log('string[]!');
}
}
另一个选项是Array.isArray()
if(! Array.isArray(classNames) ){
classNames = [classNames]
}
I know this has been answered, but TypeScript introduced type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards
If you have a type like: Object[] | string[]
Object[] | string[]
and what to do something conditionally based on what type it is - you can use this type guarding:
function isStringArray(value: any): value is string[] {
if (value instanceof Array) {
value.forEach(function(item) { // maybe only check first value?
if (typeof item !== 'string') {
return false
}
})
return true
}
return false
}
function join<T>(value: string[] | T[]) {
if (isStringArray(value)) {
return value.join(',') // value is string[] here
} else {
return value.map((x) => x.toString()).join(',') // value is T[] here
}
}
There is an issue with an empty array being typed as string[]
, but that might be okay
上一篇: 如何检查一个元素是一个数组还是单个元素