![](/img/trans.png)
[英]Should I define all (potential) properties of the base class methods in the constructor in a class? It works without
[英]TypeScript: How do you create a wrapper class that has all the methods of the base class without manually declaring?
例如,我有一个基类:
class Base {
void A();
void B();
}
我正在尝试创建一个子类:
class Sub extends Base {
bool canA() { ... }
void A() { return this.canA() ? Base.A() : undefined; }
void B() { return Base.B(); }
}
我的目标是让这个子类将覆盖所有方法Base
类,以便重写的方法将首先调用canX()
如果该方法是在定义的Sub
类,然后调用Base.X()
如果最后调用返回真正。
我当然可以手动定义这些包装器方法。 但是,最好以某种方式自动/编程地执行此操作。 我是TypeScript的新手,所以对我的问题没有任何意义感到抱歉。 有什么建议吗?
可能 ,但是很痛苦。 您遍历Base.prototype
的方法并创建包装器:
class Base {
a(): void {
// ...
}
b(): void {
// ...
}
}
class Sub extends Base {
canA(): boolean {
// ...
}
canB(): boolean {
// ...
}
}
const baseProto = Base.prototype as Record<string,any>;
const subProto = Sub.prototype as Record<string,any>;
for (const name of Object.getOwnPropertyNames(Base.prototype)) {
const method = baseProto[name];
if (typeof method === "function") {
subProto[name] = function(...args: any[]) {
if (this["can" + name.toUpperCase()]()) {
method.call(this, ...args);
}
};
}
}
上面的Playground Link加上演示其正常工作的代码。
请注意,此代码假定:
a
, b
canA
, canB
void
返回类型(否则,对包装器的处理会略有不同) 我永远不会生成方法(尽管那是可能的)。 相反,只需动态检查对象上是否存在方法:
class Base {
canA?: () => boolean;
canB?; () => boolean;
void A() {
if(this.canA && !this.canA()) return;
}
void B() {
if(this.canB && !this.canB()) return;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.