【问题标题】:How to implement a factory method in typescript?如何在打字稿中实现工厂方法?
【发布时间】:2019-02-10 08:23:13
【问题描述】:

我的代码:

class Model {}

class Loader {
    static load<M extends Model>(ModelClass: typeof Model): M {
        return new ModelClass();
    }
}

错误信息:Type 'Model' is not assignable to type 'M'.

游乐场链接:goo.gl/qrSsoX

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我们应该说load 将类作为参数而不是实例。

    export interface Type<T> extends Function { new (...args: any[]): T; }
    
    class Model {}
    
    class Loader {
        static load<M extends Model>(ModelClass: Type<M>): M {
            return new ModelClass();
        }
    }
    

    欲了解更多信息,请查看this 答案

    【讨论】:

    • 这个问题怎么解决呢?请参阅:goo.gl/DqEeBs
    • 对吗? static load&lt;M extends Model&gt;(ModelClass: Type&lt;M&gt; &amp; typeof Model): M {...
    • 我猜是这样,TypeScript 有 problemstatic 方法。
    • 由于Type&lt;T&gt;是类的静态端(即构造函数)的接口,而不是实例,所以可以直接将m1声明为Type&lt;T&gt;的方法,而无需static 修饰符。
    • 当然,如果您对与typeof Model 相交感到满意,这是一个很好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2019-01-15
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多