如何检查数组的类型? [英] How to check the type of an array?

查看:35
本文介绍了如何检查数组的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Array 表示它是字符串"类型变量的集合.

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

推荐答案

typescript 提供的类型系统在运行时不存在.
在运行时,您只有 javascript,因此唯一知道的方法是遍历数组并检查每个项目.

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.

在 javascript 中,您有两种方法可以了解值的类型,一种是 typeofinstanceof.

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

对于字符串(和其他原语)你需要 typeof:

For strings (and other primitives) you need typeof:

typeof VARIABLE === "string"

使用对象实例你需要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

(代码在操场上)

这篇关于如何检查数组的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆