Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

typescript - How to get the parent class at runtime

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...