2017-02-25 25 views
0

爲什麼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;}; 
} 

回答

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; 
} 
2

流量不喜歡這種風格。當你在同一個模塊中使用它時,它會起作用,但是當你從另一個文件中導入它時,它不會。

建議使用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;};