typescript 提供的类型系统在运行时不存在。
在运行时你只有 javascript,所以唯一知道的方法是遍历数组并检查每个项目。
在 javascript 中,您有两种方法可以知道值的类型,typeof 或 instanceof。
对于字符串(和其他原语),您需要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)