【问题标题】:Mix into abstract base class in Typescript在 Typescript 中混入抽象基类
【发布时间】:2017-10-06 16:41:41
【问题描述】:

我想在抽象基类中混入一些方法,创建一个新的抽象类。

举个例子:

abstract class Base {
    abstract method();
}

interface Feature {
    featureMethod();
}

class Implementation extends Base implements Feature {
    method() {
    }

    featureMethod() {
       // re-usable code that uses method() call
       this.method();
    }
}

这很好用,但目标是获取 Feature 接口的实现并将其移动到一个 mixin 中,以便基类的其他实现可以重用它。

我得到了以下内容,但它不能在 Typescript 2.4.1 中编译

type BaseConstructor<T = Base > = new (...args: any[]) => T;
export function MixFeature<BaseType extends BaseConstructor>(TheBase: BaseType) {
    abstract class Mixed extends TheBase implements Feature {
        featureMethod() {
            // re-usable code that uses method() call
            this.method();
        }
    }
    return Mixed;
}

class Implementation extends MixFeature(Base) {
    method() {
    }
}

但是Typescript不赞成,说:

Error:(59, 41) TS2345:Argument of type 'typeof Base' is not assignable to parameter of type 'BaseConstructor<Base>'.
Cannot assign an abstract constructor type to a non-abstract constructor type.

是否有可能完成这项工作,或者是 Typescript 限制不能使用 mixins 扩展抽象基础?

【问题讨论】:

    标签: typescript abstract mixins


    【解决方案1】:

    目前没有办法在 TypeScript 中描述抽象类构造函数的类型。 GitHub 问题 Microsoft/TypeScript#5843 跟踪此问题。你可以在那里寻找想法。一个建议是,您可以通过简单地断言 BaseBaseConstructor 来抑制错误:

    // no error
    class Implementation extends MixFeature(Base as BaseConstructor) {
        method() {
        }
    }
    

    现在您的代码可以编译了。但请注意,由于无法指定 BaseConstructor 表示 abstract 构造函数,因此无论您是否愿意,返回的类都将被解释为具体的,尽管 Mixed 是声明为abstract:

    // also no error; may be surprising
    new (MixFeature(Base as BaseConstructor));
    

    因此,如果您想将 mixin 与抽象类一起使用,那么现在您只需要小心。祝你好运!

    【讨论】:

      猜你喜欢
      • 2018-07-11
      • 1970-01-01
      • 2016-08-18
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多