2016-09-10 8 views
5

ES6 mix-inのTypescript定義を記述する方法はありますか?ES6ミックスインのTypescript定義

私はlibrary.jsでこのパターンをした、と私はlibrary.d.ts

// declaration in `library.js` 
class Super extends Simple { 
    constructor() {} 

    static Compose(Base = Super) { 
     return class extends Base { 
      // ...  
     } 

    } 
} 

// usage in `client.js` 
class MyClass extends Super.Compose() {} 
let myInstance = new MyClass(); 

class MyOtherClass extends Super.Compose(AnotherClass) {} 

答えて

4

を作成したいと思いません、活字体の型システムは、そのための十分な表現力ではありません - https://github.com/Microsoft/TypeScript/issues/7225https://github.com/Microsoft/TypeScript/issues/4890での議論を参照してください。

typescriptですにおける慣用「クラスの種類が」

interface Constructor<T> { 
    new (...args): T; 
} 

として書かれているので、作曲のための宣言を記述するための1つの方法は

export declare class Simple {} 

export declare class Super extends Simple { 
    static Compose<T>(Base?: Constructor<T>): Constructor<T & {/*mixed-in declarations*/}> 
} 

で戻り値の型を作曲、すなわちであると宣言されます交差点型のコンストラクタ - ミックスインのすべてのプロパティと共にパラメータ(Base)のすべてのプロパティを持たなければならない型。あなたはその宣言を使用することができます

この

import {Super} from './library' 

let MyComposed = Super.Compose(Super) 
let myInstance = new MyComposed 

マイナー不便のように(それはlibrary.d.tsファイル内だと仮定)は、あなたが常にSuper.Compose()型推論ための引数を提供する必要がありますdefaultパラメータの値を知らなくても動作せず、宣言ファイルのデフォルトパラメータの値を指定することはできません。

しかし、大きな問題は、あなたが本当にクラスとして作曲の結果を使用することができないということです。

class MyClass extends Super.Compose(Super) {} 

が原因上記の問題のためにコンパイルされません。

error TS2509: Base constructor return type 'Super & {}' is not a class or interface type. 
+0

偉大な説明を、ありがとう。トラッキングhttps://github.com/Microsoft/TypeScript/issues/4890 – trefeater

+0

https://github.com/therror/therrorでは、これはmixinが返すクラスのシェイプをエクスポートすることによって実現され、開発者はコードで新しいシェイプを定義する必要がありますhttps://github.com/therror/therror #typescript-limitation – trefeater

関連する問題