Test for array of string type in TypeScript

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[]!');
   }
}

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)

Another option is Array.isArray()

if(! Array.isArray(classNames) ){
    classNames = [classNames]
}

Here is the most concise solution so far:

function isArrayOfStrings(value: unknown): value is string[] {
   return Array.isArray(value) && value.every(item => typeof item === "string");
}

Note that value.every returns true for an empty array. To return false for an empty array, add value.length > 0 to the condition clause:

function isNonEmptyArrayOfStrings(value: unknown): value is string[] {
    return Array.isArray(value) && value.length > 0 && value.every(item => typeof item === "string");
}

There is no any run-time type information in TypeScript (and there won't be, see TypeScript Design Goals > Non goals, 5), so there is no way to get the "type" of elements of an empty array. For non-empty array all you can do is to check the type of its items, one by one.

Type predicate value is string[] narrows type of value to string[] in the corresponding scope. This is a TypeScript feature, the real return type of the function is boolean.

Tags:

Typescript