获取类的属性类型

时间:2019-05-31 17:15:29

标签: angular typescript

我想获取对象类的所有属性类型

export class Test extends BaseModel
{
    id: number;
    zone: CheckZone;
    employee: Employee;

    constructor() {
        super();
        this.id = 0;
        this.zone = null;
        this.employee = null;
    }
}

// Printing the object properties and types
const object = new Test();
object.zone = new CheckZone();

for (const property in object) {
      if (object.hasOwnProperty(property)) {
        let propertyType = typeof object[property];
        if (typeof object[property] === 'object') {
          if (object[property] && object[property].constructor){
            propertyType =  object[property].constructor;
          } else {
           propertyType = null;
          }
        }
        console.log('Name: ', property, 'Type: ', propertyType, 'Value: ', object[property]);
      }
    }

/*
 * Console logs results 
 * 
Obtained
Name:  id   Type:  number           Value:  0 
Name:  zone     Type:  CheckZone() {...}    Value:  CheckZone {...}
Name:  employee Type:  null             Value:  null
Required
Name:  id   Type:  number           Value:  0 
Name:  zone     Type:  CheckZone() {...}    Value:  CheckZone {...}
Name:  employee Type:  Employee ** HERE **  Value:  null

Cannot get Employee because value is null
*/


我想获取定义为type的属性的类名,即使它为null 类型:对象->类型:CheckZone 类型:对象->类型:员工

0 个答案:

没有答案