2017-10-06 4 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(); 
    } 
} 

これは正常に動作しますが、それは、他の実装で再利用できるように目標が機能インタフェースの実装を取り、ミックスインに移動することですベースクラス。

私は、次に持っているが、それは活字体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の制限ですか?

答えて

0

現在のところ、抽象クラスのコンストラクタの型をTypeScriptで記述する方法はありません。 GitHub Issue Microsoft/TypeScript#5843これを追跡します。そこにあなたのアイデアを見ることができます。

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

今、あなたのコードがコンパイルされます:1つの提案は、あなたは、単にBaseBaseConstructorであることを表明することによって、エラーを抑制することができるということです。

// also no error; may be surprising 
new (MixFeature(Base as BaseConstructor)); 
:しかし BaseConstructor抽象コンストラクタを表すことを指定する方法がないので、返されたクラスは Mixedabstractとして宣言されているという事実にもかかわらず、あなたがそれにかないかどうかを、具体的なものとして解釈されることに注意

今のところ、抽象クラスでミックスインを使用する場合は注意が必要です。がんばろう!

関連する問題