patterntypescriptCritical
Test for array of string type in TypeScript
Viewed 0 times
stringtesttypefortypescriptarray
Problem
How can I test if a variable is an array of string in TypeScript? Something like this:
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.
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
You cannot test for
If you specifically want for
In case you need to check for an array of a class (not a basic type)
If you are not sure that all items are same type
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[]!');
}
}In case you need to check for an array of a class (not a basic type)
if(items && (items.length > 0) && (items[0] instanceof MyClassName))
If you are not sure that all items are same type
items.every(it => it instanceof MyClassName)
Code Snippets
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[]!');
}
}Context
Stack Overflow Q#23130292, score: 305
Revisions (0)
No revisions yet.