Flowtype不检测对象内的属性类型

时间:2016-12-09 23:04:29

标签: javascript flowtype

我遇到以下错误

 90:             var b = action.data;
                                ^^^^ property `data`. Property not found in
 90:             var b = action.data;
                         ^^^^^^ object type

这是一个函数,它接收action作为参数,如下所示:

export default (state: SecurityGroupState = { groups: null, editingIPRange: null }, action: Action) => {

使用Action导入类型import type,如下所示:

import type { Action } from "../../actions";

它被声明为:

export type Action = {
    type: string,
    data: Object,
} | {
    type: string,
    error: Object,
};

触发初始错误的代码如下:

switch (action.type) {
case GET:
    if (action.error) {
        console.error(action.error);
        break;
    }

    var a = action.data; // no error here
    const groupsCopy2 = _.map(state.groups, () => {
        var b = action.data;
    });
}

因此,在var a = ...行中,action.data可以使用Flow,但在map lambda内部,它似乎不知道action: Action可以拥有data 1}}密钥。

1 个答案:

答案 0 :(得分:2)

Flow对优化很悲观,它认为每个函数调用都可以修改action.data。至于修复方法,您可以使用const binding

const data = action.data
const groupsCopy2 = _.map(state.groups, () => {
  var b = data;
});