mercredi 31 janvier 2018

Read properties of object at run time even when they are not initialized

I am interested in creating a class decorator in typescript that can hold the class members information at runtime, which is quite similar to reflection API in C# and Java. Consider following example

class Address {
   door: number;
}
class Order {
   id: number;
}
class Customer {
   id: number;
   name: string;
   present: Address;
   orders: Order[];
}

let x = new Customer();
console.log(x); // outputs an empty object and no properties are visible 
       // because properties are mapped to object only after initialization.

I would like to get property details of a class even when they are not initialized. is it possible using decorators? I am thinking to create Model decorator

@Model({
   id: Number.prototype,
   name: String.prototype,
   present: Address.prototype,
   orders: // challenge is How do I specify array of specific type? 
   // because arrays in javascript simply inherit from Array.prototype 
   // but it must be Array of Order.prototype
})
class Customer {
   id: number;
   name: string;
   present: Address;
   orders: Order[];
}

Is this a better approach? Are there any open libraries that solve this problem in typescript. Any help is greatly appreciated. What I would like to see the output is

class members {
    static show(o: any){
      // should loop through the properties of object even not initialized
    }
}

members.show(new Customer()); // should display all properties with default values; 
// null for reference types and values for value types





Aucun commentaire:

Enregistrer un commentaire