如何获取类的变量的数据类型?

时间:2018-04-16 06:12:57

标签: javascript typescript

我喜欢上课

 export class Model {
   name: string;
   size: number;
}

如果我尝试获取下面这些变量的类型,则返回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 = function(obj) {
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
  }

console.log( this.toType (this.model.size));

返回null。

如何在不指定值的情况下正确获取变量类型?

2 个答案:

答案 0 :(得分:2)

您可以将emitDecoratorMetadataexperimentalDecorators选项与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

答案 1 :(得分:0)

您共享的许多代码似乎都不是有效的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