5

Is there a way to check what the array "type" is? for example

Array<string> means it is a collection of "string" type variables.

so if i create a function

checkType(myArray:Array<any>){
  if(/*myArray is a collection of strings is true*/){
    console.log("yes it is")
  }else{
    console.log("no it is not")
  }
}
Newbie2016
  • 517
  • 3
  • 6
  • 11

1 Answers1

7

The type system that typescript offers doesn't exist at runtime.
At runtime you only have javascript, so the only way to know is to iterate over the array and check each item.

In javascript you have two ways of knowing a type of a value, either with typeof or instanceof.

For strings (and other primitives) you need typeof:

typeof VARIABLE === "string"

With object instance you need instanceof:

VARIABLE instanceof CLASS

Here's a generic solution for you:

function is(obj: any, type: NumberConstructor): obj is number;
function is(obj: any, type: StringConstructor): obj is string;
function is<T>(obj: any, type: { prototype: T }): obj is T;
function is(obj: any, type: any): boolean {
    const objType: string = typeof obj;
    const typeString = type.toString();
    const nameRegex: RegExp = /Arguments|Function|String|Number|Date|Array|Boolean|RegExp/;

    let typeName: string;

    if (obj && objType === "object") {
        return obj instanceof type;
    }

    if (typeString.startsWith("class ")) {
        return type.name.toLowerCase() === objType;
    }

    typeName = typeString.match(nameRegex);
    if (typeName) {
        return typeName[0].toLowerCase() === objType;
    }

    return false;
}

function checkType(myArray: any[], type: any): boolean {
    return myArray.every(item => {
        return is(item, type);
    });
}

console.log(checkType([1, 2, 3], Number)); // true
console.log(checkType([1, 2, "string"], Number)); // false


console.log(checkType(["one", "two", "three"], String)); // true

class MyClass { }
console.log(checkType([new MyClass(), new MyClass()], MyClass)); //true

(code in playground)

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299