2017-10-06 149 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)); 

所以現在你只需要小心如果你想使用混合與抽象類。祝你好運!