4

I want to access metadata of a child class in its parent's constructor before the super call.

See following example:

import "reflect-metadata";

const KEY = Symbol()
function Decorator(name: string) {
    return function(target: any) {
        Reflect.defineMetadata(KEY, name, target);
    }
}

class BaseBase {
    constructor(name: string) {
        console.log(name);
    }
}

class Base extends BaseBase {
    constructor() {
        // prints "undefined" (because its defined on the Child constructor)
        console.log(Reflect.getMetadata(KEY, Base)); 
        console.log(Reflect.getMetadata(KEY, arguments.callee)); // ERROR: deprecated and removed in ES5
        super("insert meta data here");
        // will print "ChildName" but this can not be used before super call
        console.log(Reflect.getMetadata(KEY, Reflect.getPrototypeOf(this).constructor));
        console.log(Reflect.getMetadata(KEY, this.constructor));
    }
}

@Decorator("ChildName")
class Child extends Base {}

new Child();

Is there any way to pass the metadata of the Child class down to BaseBase class?

I suppose I could access the metadata in the Child constructor and pass it to constructor call of Base, but I have many different Childs and I would like to avoid defining an constructor for all of them.

WaeCo
  • 1,155
  • 1
  • 10
  • 21

0 Answers0