2017-05-19 9 views
1

私はTypescript 2.2のmixinを使用しています。別のMixinのプロパティを使用したいと思います。TypeScript mixinは別のmixinに制約されています

ドキュメントはミックスインが唯一の特定のクラスに混合するように制約することができます...

const WithLocation = <T extends Constructor<Point>>(Base: T) => 
    class extends Base { 
     getLocation(): [number, number] { 
      return [this.x, this.y]; 
     } 
    } 

だけ別のミックスインを含むクラスにミックスするためにそれらを制約することが可能であることを示しますか?

答えて

1

はい、可能です。あなたの他のミックスインを定義して、それがインターフェースに裏打ちされるようにしてください。たとえば:

interface Named { 
    name: string; 
} 

function Named<T extends Constructor<{}>>(Base: T) { 
    return class extends Base implements Named { 
     name: string; 
    }; 
} 

その後、Constructor型引数に交差タイプでインタフェースを使用することができます。

const WithLocation = <T extends Constructor<Point & Named>>(Base: T) => 
    class extends Base { 
     getLocation(): [number, number] { 
      console.log(this.name); // compiles 
      return [this.x, this.y]; 
     } 
    }; 

const NamedPointWithLocation = WithLocation(Named(Point)); 
const PointerWithLocation = WithLocation(Point); // error, expects argument to be Named 

あなたはコンパイル時に動作すること、これがhereを行われているのより複雑な例を見ることができます宣言ファイル。

+0

素晴らしい作品 - ありがとうございます:) – JayEss