我想将一些方法混合到一个抽象基类中,以创建一个新的抽象类 .
采用以下示例:
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 回答
目前无法在TypeScript中描述抽象类构造函数的类型 . GitHub问题Microsoft/TypeScript#5843追踪这个 . 你可以在那里寻找想法 . 一个建议是你可以通过简单断言
Base
是BaseConstructor
来抑制错误:现在你的代码编译了 . 但请注意,由于无法指定
BaseConstructor
表示抽象构造函数,因此无论您是否想要它,返回的类都将被解释为具体,尽管Mixed
被声明为abstract
:所以现在,如果你想将mixins与抽象类一起使用,你必须要小心 . 祝好运!