如何检查数组的类型?

时间:2017-04-13 16:43:41

标签: typescript typescript2.0

有没有办法检查数组“类型”是什么?例如

Array<string>表示它是“字符串”类型变量的集合。

所以如果我创建一个函数

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")
  }
}

1 个答案:

答案 0 :(得分:4)

打字稿提供的类型系统在运行时不存在 在运行时你只有javascript,所以唯一知道的方法是遍历数组并检查每个项目。

在javascript中,您有两种方式可以使用typeofinstanceof来了解值的类型。

对于字符串(和其他原语),您需要typeof

typeof VARIABLE === "string"

使用对象实例,您需要instanceof

VARIABLE instanceof CLASS

这是您的通用解决方案:

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

相关问题