samedi 20 novembre 2021

Is it possible to instantiate a generic type's property through reflection?

I am trying to create an abstract class that initializes T class properties by iterating a json-style object passed in constructor.

 abstract class JSONClass<T> {
  // Receive a JSON object implementing all T properties
  constructor(json: JSONClassDictionary<T>) {
    this.fromJSON(json);
  }


  fromJSON(json: JSONClassDictionary<T>) {
    for (let key in json){
      let prop = this[key];
      if (prop is not a class) {  <// -- 1) Determine whether it's a class
        this[key] = prop;
      }
      else{
        const constructor = getConstructorOf(T[key]) // <-- 2) Get constructor of T[Key] property. This is no-sense to compiler
        this[key] = new constructor(prop)
      }
    }
  }
}

The problem is that T may have some properties which are not primitive types, and require initialization.

Example of real case scenario and invocation:

class UserRole extends JSONClass<UserRole> {
  id;
  name;
  permissionGroup: PermissionGroup;

}

const role = UserRole({
  id: 1,
  name: "Admin",
  permissionGroup: {// <-- This will be converted to PermissionGroup() in fromJSON
    id: 1,
    action: ".."  
  }
})

This means that when fromJSON is iterating through the property permissionGroup, it should not perform this[key] = prop; but this[key] = new PermissionGroup(prop).

I am having issues in Point (1) and Point (2) as shown in code comments, specifically in:

  1. Being able to determine whether the key I'm iterating in json is an instantiable class property of T, instead of a primitive type;

  2. If true, the initialize property of T.

Is this achievable?





Aucun commentaire:

Enregistrer un commentaire