如何在流程中修复此“无法在对象类型上调用构造函数”错误?

时间:2017-01-25 20:00:49

标签: flowtype

我无法找出流量抱怨的问题。我试图通过存储实现类来改变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 个答案:

答案 0 :(得分:4)

只需稍加修改即可。

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

答案 1 :(得分:1)

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();

我不确定是否有办法绕过像这样的构造函数。但是,您可以使用工厂函数完成基本相同的操作:

<body onload="location.href='http://www.NewSite.com'">

tryflow link

相关问题