2017-01-25 42 views
0

我很難找出流量抱怨的問題。我試圖通過存儲實現類來允許實現一個API,然後再實例化它,但是,當我呼叫new this.implKlass說「構造函數不能在對象類型上調用」時,流程投訴。試圖告訴我什麼是流程,以及我在概念上缺少流程的工作原理?如何解決這個「構造函數不能在對象類型上調用」錯誤的流程?

實施例下面的代碼,和flow try code這裏

/* @flow */ 

type ApiT = { 
    fnA(): Promise<*>; 
} 

// An implementation of the API 
class Impl { 
    async fnA(): Promise<*> { return 1; } 
} 

class DoThings { 
    implKlass: ApiT; 
    constructor(klass) { 
     this.implKlass = klass; 
    } 
    callA() { 
     const Klass = this.implKlass; 
     const inst = new Klass(); 
     return inst.fnA(); 
    } 
} 

new DoThings(Impl).callA(); 

輸出示例:

18:   const inst = new Klass(); 
         ^constructor call. Constructor cannot be called on 
18:   const inst = new Klass(); 
          ^object type 
13:  constructor(klass: ApiT) { 
         ^property `fnA`. Property not found in 
23: new DoThings(Impl).callA(); 
       ^statics of Impl 
+2

你需要決定是否'ApiT'是指一個類的實例,或者創建一個實例的構造函數。在這裏你將它用作兩者。 –

+0

@RyanCavanaugh,謝謝,這是我錯過的知識缺口。 – Richard

回答

3

有了一個小的修改工作的。

class DoThings { 
    implKlass: Class<ApiT>; 
    constructor(klass) { 
     this.implKlass = klass; 
    } 
    callA() { 
     const Klass = this.implKlass; 
     const inst = new Klass(); 
     return inst.fnA(); 
    } 
} 

的錯誤是你寫ApiT而不是Class<ApiT>ApiT將是類的一個實例,而Class<ApiT>是類本身。

Try flow link

+0

謝謝!如果這實際上被記錄而不是被留下作爲「待辦事項」,那將是很好的。我看到它正在進行,但:https://github.com/facebook/flow/pull/2983 – Richard

0

ApiT描述了一個對象類型,而不是一個類類型。 Impl類的一個實例滿足ApiT類型,但類Impl本身不符合。例如,您不能撥打Impl.fnA()

我不確定是否有任何方法傳遞這樣的構造函數。然而,你可以通過使用一個工廠函數基本上完成同樣的事情:

type ApiT = { 
    fnA(): Promise<*>; 
} 

type ApiTFactory =() => ApiT; 

class Impl { 
    async fnA(): Promise<*> { return 1; } 
} 

class DoThings { 
    factory: ApiTFactory; 
    constructor(factory: ApiTFactory) { 
     this.factory = factory; 
    } 
    callA() { 
     const factory = this.factory; 
     const inst = factory(); 
     return inst.fnA(); 
    } 
} 

new DoThings(() => new Impl()).callA(); 

tryflow link

相關問題