[英]How to get the parent class at runtime
Is it possible to get the parent class of a TypeScript class at runtime?是否可以在运行时获取 TypeScript 类的父类? 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
.在装饰器中,我想要一个
AbstractClass
的实例。
Thanks very much for your help!非常感谢您的帮助!
You can use the Object.getPrototypeOf function. 您可以使用Object.getPrototypeOf函数。
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): 代码 @DavidSherret添加(在评论中),这是你想要的(我认为):
export function CustomDecorator(data: any) {
return function (target: Function) {
var parentTarget = target.prototype;
...
}
}
Or as @DavidSherret noted: 或者@DavidSherret指出:
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 :)
}
}
For me following construct worked for getting base type constructor from a type constructor:对我来说,以下构造可用于从类型构造函数中获取基类型构造函数:
class Validator {
constructor(private readonly ctr: ConstructorFunction<T>) {
this.id = ctr.name;
//...
let protoRef = ctr['__proto__'] as Function;
this._inheritFrom = protoRef && protoRef !== Object ? protoRef.name : null;
this._inheritsFromValidator = null;
//...
}
}
Yeah this is not sound as fancy as smth as ctr.getBaseClassConstructor()
a-la是的,这听起来不像
ctr.getBaseClassConstructor()
a-la 那样花哨
type BaseType<T> = [some-magic]<T>
function getBasicType<T>():BaseType<T>;
but that trick with __proto__
work.但是
__proto__
技巧起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.