【问题标题】:How to check the type of an array?如何检查数组的类型?
【发布时间】:2017-09-09 21:25:41
【问题描述】:

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

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

【问题讨论】:

  • 嗯,什么?不清楚你在问什么
  • 你的问题不太清楚。
  • 所以说你的数组已经被声明为字符串的集合。有没有办法检查它是否是字符串的集合,你可以用集合对象类来做吗?
  • 运行时没有类型系统。
  • 对不起,如果不清楚,我会写更多的代码来帮助我想要找到的东西。

标签: typescript typescript2.0


【解决方案1】:

typescript 提供的类型系统在运行时不存在。
在运行时你只有 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多