Flowtype 未检测对象内部 属性 的类型

Flowtype not detecting type of property inside object

我遇到了以下错误

 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 = ... 行中,Flow 可以使用 action.data,但是在 map lambda 中它似乎不知道 action: Action 可以有一个data键。

Flow 对细化持悲观态度,它认为每个函数调用都可以修改action.data。至于修复,您可以使用 const binding

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