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.
Solution 1:
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)
).
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[]!');
}
}
Solution 2:
Another option is Array.isArray()
if(! Array.isArray(classNames) ){
classNames = [classNames]
}