简单构造函数中的Flowtype错误

时间:2017-02-25 09:33:46

标签: javascript constructor flowtype

为什么flowtype会报告以下错误,以及如何将其记录为按预期工作?

index.js:7
  4: console.log(MY_OBJECT.getName());
                           ^^^^^^^ property `getName`. Property not found in
  4: console.log(MY_OBJECT.getName());
                 ^^^^^^^^^ new object

index.js

// @flow
import {MyObject} from './object';
const MY_OBJECT = new MyObject('name');
console.log(MY_OBJECT.getName());

object.js:

// @flow
export function MyObject(name: string) {
    this._name = name;
    this.getName = function (): string {return this._name;};
    this.setName = function (name: string) {this._name = name;};
}

2 个答案:

答案 0 :(得分:2)

Flow并不喜欢这种风格。当你在同一个模块中使用它时,它会起作用,但是当你从另一个文件中导入它时,它就不会。

建议改为使用ES2015 class syntax

// @flow
export class MyObject {
    name: string;

    constructor(name: string){
        this.name = name;
    }

    getName() {
        return this.name;
    }

    setName(name: string) {
        this.name = name;
    }
}

如果您不喜欢这样,可以使用原型has limited support

// @flow
export function MyObject(name: string) {
  this._name = name;        
}

MyObject.prototype.getName = function (): string {return this._name;};
MyObject.prototype.setName = function (name: string) {this._name = name;};

答案 1 :(得分:1)

我只是想通了,当它明确地返回时它确实有效:

// @flow
export function MyObject(name: string) {
    this._name = name;
    this.getName = function (): string {return this._name;};
    this.setName = function (name: string) {this._name = name;};
    return this;
}