问题描述
我正在用Typescript构建类系统.有一个主要的抽象类Component
,它具有静态方法create()
.将在子级上调用此方法来构建特定实例
I am building a class system in Typescript. There is a main abstract class Component
, that has a static method create()
. This method will be called on children to build a particular instance
abstract class Component {
static build() {
// some additional logic here, for example, cache to reuse instances
return new this();
}
}
class Button extends Component { }
class Input extends Component {}
Button.build(); // returns Button instance
Input.build(); // returns Input instance
这种方法在Javascript中效果很好,但是Typescript在new this()
行报告了一个错误,说无法创建抽象类的实例."
This approach works well in Javascript, but Typescript reports an error at the line new this()
, saying "Cannot create an instance of an abstract class."
如何解释打字稿,该方法将在派生实例上调用,而不是直接在主抽象类上调用?也许还有其他方法可以实现我需要的API?
How can I explain typescript that method will be called on derived instances, but not on the main abstract class directly? Maybe there are other ways to implement the API that I needed?
推荐答案
this
是typeof Component
,并且由于Component
是抽象类,所以new this
是不允许的.即使Component
不是抽象的,在子类中也无法正确处理Button.build()
返回类型.
this
is typeof Component
, and since Component
is abstract class, new this
is inadmissible. Even if Component
wasn't abstract, Button.build()
return type wouldn't be properly handled in child classes.
它需要通过通用方法进行提示的类型:
It requires some type hinting, via generic method:
abstract class Component {
static build<T = Component>(this: { new(): T }) {
return new this();
}
}
class Button extends Component { }
const button = Button.build<Button>(); // button: Button
这篇关于抽象类中的静态工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!