0

I want to get all properties types of object class

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
*/


I want to get the class name of a property defined as type even if it is null Type: object --> Type: CheckZone Type: object --> Type: Employee

  • Possible duplicate of [Get properties of a class using Typescript](https://stackoverflow.com/questions/40636292/get-properties-of-a-class-using-typescript) – nircraft May 31 '19 at 17:19
  • TypeScript does not emit runtime type information, so you can't get that information at runtime (by iterating over object properties). You *might* be able to get an instance's constructor name via `instance.constructor.name`. – Aaron Beall May 31 '19 at 17:22
  • 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]); } } Name: id Type: number Value: 0 Name: zone Type: CheckZone() {} Value: CheckZone {} Name: employee Type: null Value: null is null cannot get the constructor – Jose Colman May 31 '19 at 17:48

0 Answers0