2017-01-25 41 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

相关问题