2017-02-06 25 views
0

私はプラグインbabelを使用して動的に型をチェックしたjavascriptコードを生成しています。以下は、このコンパイルされたコードのコードフローランタイムを使用してJavascriptでインターフェイスを実装する

  • 実行を型検査するために、フロー注釈を変換するために、バベルを使用してこのコードをコンパイル私は

    • は(フロー注釈付き)静的javascriptのコードを書く使用していたワークフロー

    • ですin node.js

    次のワークフローでは、タイプコードタイプのコードを書くことができますが、タイプche私が欲しいところにしか居ません。

    だから、今、私たちは私がやっているものを理解することを、私は、私は基本的にそれがのように聞こえる正確に何をしますInterfaceと呼ばれるクラスを、構築する必要があり

    達成しようとしているかを説明しましょう。このクラスは、インターフェースであると思われるクラスによって拡張され、他のクラスによって拡張されます。このような何か:

    class Interface() { 
        constructor() { 
         ... 
        } 
    
        // interface superclass, supposed to be extended by all interfaces 
        // this class will provide all the utility methods required 
        // by an interface, such as validating the implementation of the 
        // interface, ... 
    
        validateInterfaceImplementation() { 
         ... 
        } 
    } 
    
    // interface definition 
    class FooInterface extends Interface { 
        constructor() { 
         super(); 
         ... 
        } 
    } 
    
    // actual class, that will implement the "FooInterface" interface 
    class Foo extends FooInterface { 
        constructor() { 
         super(); 
         ... 
        } 
    } 
    

    今、私はFooInterfaceの厳格な実施を強制します。これは、私がFooInterface interfaceが実装すると予想されるすべてのメソッドと、これらすべてのメソッドがFooクラスによって実装されていることの検証を定義する方法を必要としていることを意味します。

    私が試してみました、私はこのアプローチには複数の問題

    • 私はジェネリッククラスInterface<T>を実装する方法を確認していないに直面しています。この

      // interface.js 
      // @flow-runtime 
      class Interface<T> { 
          constructor(t: T) { 
           (this: T); // let flow validate that the interface is implemented 
          } 
      } 
      
      // FooInterface.js 
      // @flow-runtime 
      type foInterface = { 
          bar(param: string): number; 
      } 
      
      class FooInterface extends Interface<fooInterface> { 
          constructor() { 
           super(fooInterface); 
          } 
      } 
      
      // Foo.js 
      // @flow-runtime 
      class Foo extends FooInterface { 
      
      } 
      
      new Foo(); // should throw an error, because the interface is not implemented 
            // (the function bar is not defined) 
      

      ようになります。私の実装が間違っていると思います。コンパイルされたbabelコードもエラーをスローしますが、これを行う方法を理解することはできません。

    • この方法が動作するかどうか、またはこれがこの問題に近づく最善の方法であるかどうかはわかりません。

    何か歓迎します。ありがとうございます。

  • 答えて

    1

    flow-runtime 0.5.0では、フローのimplementsキーワードとFlowインターフェイスを組み合わせて使用​​できます。私は、具体的な授業をまったく作成することなく、あなたが望むものをあなたに与えることができると思います。

    // @flow 
    // @flow-runtime 
    interface IPoint<T> { 
        x: T; 
        y: T; 
    } 
    
    interface IJSON { 
        toJSON(): any; 
    } 
    
    class Point implements IPoint<number>, IJSON { 
        x: number = 123; 
        y: number = 456; 
        toJSON() { 
        return {x: this.x, y: this.y}; 
        } 
    } 
    
    関連する問題