在 TypeScript 中,有没有一种方法可以让类在子类化时以一种有效的方式引用其构造函数?
abstract class Base<T> {
constructor(readonly value: T) {}
abstract getName(): string;
clone() {
const Cls = this.constructor;
return new Cls(this.value);
}
}
在这个片段中,Cls
被赋予了 Function
类型,因此编译器会提示:“不能将‘new’与类型缺少调用或构造的表达式一起使用签名。”
最佳答案
Typescript 不对构造函数使用严格类型(它仅使用 Function
)并且由于这不是构造函数,因此不能使用 new
调用它.
简单的解决方案是使用类型断言:
abstract class Base<T> {
constructor(readonly value: T) { }
abstract getName(): string;
clone() {
// Using polymorphic this ensures the return type is correct in derived types
const Cls = this.constructor as new (value: T) => this;
return new Cls(this.value);
}
}
关于typescript - 在 TypeScript 中编写通用克隆方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325751/