typescript 如何检查数组的类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43397634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check the type of an array?
提问by Newbie2016
Is there a way to check what the array "type" is? for example
有没有办法检查数组“类型”是什么?例如
Array<string>
means it is a collection of "string" type variables.
Array<string>
意味着它是“字符串”类型变量的集合。
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")
}
}
回答by Nitzan Tomer
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.
typescript 提供的类型系统在运行时不存在。
在运行时,您只有 javascript,因此唯一知道的方法是遍历数组并检查每个项目。
In javascript you have two ways of knowing a type of a value, either with typeofor instanceof.
在 javascript 中,您有两种方法可以了解值的类型,即typeof或instanceof。
For strings (and other primitives) you need typeof
:
对于字符串(和其他原语),您需要typeof
:
typeof VARIABLE === "string"
With object instance you need instanceof
:
使用对象实例,您需要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
(操场上的代码)