javascript - 如何获取类的变量的数据类型?
我有课像
export class Model {
name: string;
size: number;
}
如果我像下面这样尝试获取这些变量的 typeof,它会返回 undefined。
model: Model;
.
.
.
this.model = new Model();
console.log(typeof (this.model.size));
我尝试创建一个带构造函数的类。
export class Model{
constructor(public q: string, public size?: number) {}
}
我试图获取变量的类型。
this.model = new Model('', null);
console.log(this.model.size)
它返回对象。我尝试了 toType 方法
toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
和
console.log( this.toType (this.model.size));
它返回空值。
我如何在不赋值的情况下正确获取变量类型?
答案#1
您可以将 emitDecoratorMetadata 和 experimentalDecorators 选项与 reflect-metadata 包一起使用
import 'reflect-metadata'
// Decorator does nothing but metadata is emitted only for decorated symbols by the compiler so we need an empty decorator
function EmitType(target: Object, propertyKey: string | symbol){
}
export class Model {
@EmitType name: string;
@EmitType size: number;
@EmitType child: Model;
@EmitType data : { test: string };
}
// Will output function String() { … }
console.log(Reflect.getMetadata("design:type", Model.prototype, "name"));
// Will output function Number() { … }
console.log(Reflect.getMetadata("design:type", Model.prototype, "size"));
// Will output function Model() { … }
console.log(Reflect.getMetadata("design:type", Model.prototype, "child"));
// Will output function Object() { … }
console.log(Reflect.getMetadata("design:type", Model.prototype, "data"));
作为元数据存储的值是类型构造函数,因此对于自定义类,它将是类的构造函数。对于没有构造函数的接口和其他类型,类型将始终是 Object
答案#2
你分享的很多代码看起来并不是有效的JS。我注意到的另一种模式是,你实际上从未在类中将值分配给实例属性。
这里有一个简单的例子。希望它有帮助。
class Test {
constructor(a,b){
// Make sure you assign the values to instance properties
this.a = a;
this.b = b;
}
}
// Create a new instance passing different typed arguments
var t = new Test('one',1);
// Test the types
console.log(typeof t.a); //string
console.log(typeof t.b); //number