流程,可选的泛型被赋予类型,但在未定义的错误中缺少get属性

时间:2018-12-10 06:17:26

标签: javascript flowtype

TAction这样的类型

export type TAction<TPayload = any> = {
  +type: string,
  payload?: TPayload
};

在这里,我给它TPayload

(
  state: TSettings,
  action: TAction<{ key: any, value: any }>
) => ({
    ...state,
    [action.payload.key]: action.payload.value
}),

但是流程给我错误

Cannot get action.payload.key because property key is missing in undefined [1].

1 个答案:

答案 0 :(得分:0)

您已将payload标记为maybe type(问号),因此它可能是nullundefined

删除问号:

export type TAction<TPayload = any> = {
  +type: string,
  payload: TPayload
};

或添加检查是否已定义payload,即:

(
  state: TSettings,
  action: TAction<{ key: any, value: any }>
) => action.payload ? ({
    ...state,
    [action.payload.key]: action.payload.value
}) : {...state},