'Is there a way to use typescript or ES7 decorators on members of types?

I'm attempting to set up a simple reflection system using TypeScript or ES7 decorators but am running into an issue in relation to instances wherein only a class is available and not an instance of a class with relation to member decorators. An example of this follows, wherein I would like to be able to access the _foo decorator of DBType without having an instance of the class A available to work with:

console.clear();

function initializeReflection(target) {
    if (target.__reflection) return;
    target.__reflection = {
        classAttributes: [],
        methodAttributes: { },
        propertyAttributes: { },
        accessorAttributes: { }
    }
}

function initializeReflectionMethod(target, name) {
    initializeReflection(target);
    if (target.__reflection)
    if (target.__reflection.methodAttributes[name]) return;
    target.__reflection.methodAttributes[name] = [];
}

function initializeReflectionProperty(target, name) {
    initializeReflection(target);
    if (target.__reflection)
    if (target.__reflection.propertyAttributes[name]) return;
    target.__reflection.propertyAttributes[name] = [];
}

function initializeReflectionAccessor(target, name) {
    initializeReflection(target);
    if (target.__reflection)
    if (target.__reflection.accessorAttributes[name]) return;
    target.__reflection.accessorAttributes[name] = [];
}

function reflectionOf(target) {
    let ret = target;
    if (target.__proto__) ret = target.__proto__;
    return ret.__reflection;
}

function DBType(dbType) {
    if (!(this instanceof DBType)) return function (target, name) {
        initializeReflectionProperty(target, name);
        target.__reflection.propertyAttributes[name].push(new DBType(dbType));
    };
    this._dbType = dbType;
    this.toString = () => {
        return "DBType: " + this._dbType;
    }
}

class A {
    @DBType('VARCHAR(1)')
    _foo = 'a';
}

let a = new A();


console.log('A');
console.log(A, reflectionOf(A));

console.log('a');
console.log(a, reflectionOf(a));

console.log(a.__proto__.__reflection.propertyAttributes._foo[0].toString());

Output:

"A"



class A {
  constructor() {
      _initDefineProp(this, '_foo', _descriptor, this);
  }

}, undefined



"a"



{
  __reflection: {
    accessorAttributes: { ... },
    classAttributes: [],
    methodAttributes: { ... },
    propertyAttributes: { ... }
  },
  _foo: "a"
}, [circular object Object]



"DBType: VARCHAR(1)"

Are decorators even applied to property members prior to instantiation, and if not is there some workaround for this use case which doesn't make the code horribly bloated?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source