抽象类中的静态工厂方法 [英] Static factory method in abstract class

查看:103
本文介绍了抽象类中的静态工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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?

推荐答案

thistypeof 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

这篇关于抽象类中的静态工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆