New*_*016 5 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")
}
}
Run Code Online (Sandbox Code Playgroud)
typescript 提供的类型系统在运行时不存在。
在运行时,您只有 javascript,因此唯一知道的方法是遍历数组并检查每个项目。
在 javascript 中,您可以通过两种方式了解值的类型,即typeof或instanceof。
对于字符串(和其他原语),您需要typeof:
typeof VARIABLE === "string"
Run Code Online (Sandbox Code Playgroud)
使用对象实例,您需要instanceof:
VARIABLE instanceof CLASS
Run Code Online (Sandbox Code Playgroud)
这是一个通用的解决方案:
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
Run Code Online (Sandbox Code Playgroud)
(操场上的代码)
| 归档时间: |
|
| 查看次数: |
14072 次 |
| 最近记录: |