Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the parent class at runtime

Tags:

typescript

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!

like image 684
Thierry Templier Avatar asked Apr 26 '16 13:04

Thierry Templier


1 Answers

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 :)
    }
}
like image 52
Nitzan Tomer Avatar answered Oct 12 '22 09:10

Nitzan Tomer