NodeJS 一个函数,用于返回一个类,该类扩展了抽象类的派生类

4dc9hkyq  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(111)

我想做一个函数来返回一个类,它扩展了Typescript中抽象类的派生类。我认为抽象构造签名应该是我应该使用的。但是,Typescript提示“Non-abstract class 'SayHelloDerived' does not implement all abstract members of 'Base'.”下面是一段简化的代码。

// @errors: 18052
abstract class Base {
  abstract getName(): string;
  printName() {
    console.log("a")
  }
}
class Derived extends Base {
  getName() {
    return "";
  }
}
function makeSayHelloDerived(DerivedBase: new () => Base) {
  return class SayHelloDerived extends DerivedBase {
    sayHello() {
      console.log("hello!");
    }
  }
}

const Derived2 = makeSayHelloDerived(Derived);
const derived2 = new Derived2;
derived2.sayHello();

const Derived3 = makeSayHelloDerived(Base);
const derived3 = new Derived3;
derived3.sayHello();

Typescript Playground链接
第二个错误是预期的,但第一个错误不是。
我希望Typescript可以将函数“makeSayHelloDerived”中的参数“DerivedBase”识别为抽象“Base”类的派生类。它不应该提示任何错误,但它现在提示。我在谷歌上搜索了一下“抽象构造签名”,但没有找到。我做错什么了吗?

iovurdzv

iovurdzv1#

简单的解决方案是将参数的类型更改为new () => Derived,但我认为这不是您想要的-您希望接受从Base继承的 * 任何 * 非抽象类。
我不确定这到底是如何工作的,但我设法通过显式地将具体方法签名添加到构造签名的类型中来做到这一点:

function makeSayHelloDerived(DerivedBase: new () => Base & { getName(): string }) {
  return class SayHelloDerived extends DerivedBase {
    sayHello() {
      console.log("hello!");
    }
  }
}

相关问题