首页 文章

混合到Typescript中的抽象基类

提问于
浏览
1

我想将一些方法混合到一个抽象基类中,以创建一个新的抽象类 .

采用以下示例:

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,以便其他Base类的实现可以重用它 .

我有以下内容,但它不能在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() {
    }
}

但是打字稿不赞成,说:

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限制,抽象基础不能使用mixin扩展?

1 回答

  • 1

    目前无法在TypeScript中描述抽象类构造函数的类型 . GitHub问题Microsoft/TypeScript#5843追踪这个 . 你可以在那里寻找想法 . 一个建议是你可以通过简单断言 BaseBaseConstructor 来抑制错误:

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

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

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

    所以现在,如果你想将mixins与抽象类一起使用,你必须要小心 . 祝好运!

相关问题