2017-10-06 141 views
0

我想将某些方法混合到一个抽象基类中来创建一个新的抽象类。在Typescript中混入抽象基类中

看看下面的例子:

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(); 
    } 
} 

这工作得很好,但我们的目标是走型接口的实现,并将其移动到一个mixin,因此它可以被重新使用的其他实现基类。

我有以下内容,但它并没有在打字稿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限制,抽象的基础不能使用mixins扩展?

回答

0

目前没有办法在TypeScript中描述抽象类构造函数的类型。 GitHub Issue 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)); 

所以现在你只需要小心如果你想使用混合与抽象类。祝你好运!