2017-02-25 10 views
0

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

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