gpt4 book ai didi

javascript - TypeScript:如何创建一个具有基类所有方法而无需手动声明的包装类?

转载 作者:行者123 更新时间:2023-11-28 14:15:21 25 4
gpt4 key购买 nike

例如,我有一个基类:

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()如果最后一次调用返回 true。

我当然可以手动定义那些包装方法;然而,以某种方式自动/编程地完成它会很好。我对 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上面的代码加上演示它工作的代码。

请注意,此代码假设:

  1. 这些方法具有小写名称(JavaScript 和 TypeScript 中的标准),例如ab
  2. “can”方法是带有“can”前缀的小写名称,例如canAcanB
  3. 这些方法都有 void 返回类型(否则,您的包装器会略有不同)

关于javascript - TypeScript:如何创建一个具有基类所有方法而无需手动声明的包装类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57738464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com