How to get the parent class at runtime

2020-02-10 19:09发布

Is it possible to get the parent class of a TypeScript class at runtime? I mean, for example, within a decorator:

export function CustomDecorator(data: any) {
  return function (target: Function) {
    var parentTarget = ?
  }
}

My custom decorator is applied this way:

export class AbstractClass {
  (...)
}

@CustomDecorator({
  (...)
})
export class SubClass extends AbstractClass {
  (...)
}

Within the decorator, I would like to have an instance to AbstractClass.

Thanks very much for your help!

标签: typescript
1条回答
▲ chillily
2楼-- · 2020-02-10 19:55

You can use the Object.getPrototypeOf function.

Something like:

class A {
    constructor() {}
}

class B extends A {
    constructor() {
        super();
    }
}

class C extends B {
    constructor() {
        super();
    }
}

var a = new A();
var b = new B();
var c = new C();

Object.getPrototypeOf(a); // returns Object {}
Object.getPrototypeOf(b); // returns A {}
Object.getPrototypeOf(c); // returns B {}

Edit

After the code @DavidSherret added (in a comment), here's what you want (I think):

export function CustomDecorator(data: any) {
  return function (target: Function) {
    var parentTarget = target.prototype;
    ...
  }
}

Or as @DavidSherret noted:

function CustomDecorator(data: any) {
  return function (target: Function) {
    console.log(Object.getPrototypeOf(new (target as any)));
  }
}

2nd Edit

Ok, so here's what I hope to be you goal:

function CustomDecorator(data: any) {
    return function (target: Function) {
        var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
        console.log(parentTarget === AbstractClass); // true :)
    }
}
查看更多
登录 后发表回答