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!
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 {}
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)));
}
}
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 :)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With