我在flow docs基本上执行基本的redux-reducer示例时遇到了流错误。
此处添加到代码中的流出错:在REMOVE
开关案例上:action
未解析为正确的类型。
如果我将鼠标悬停在vscode中的payload
上,则会在ADD
情况下将其显示为AddAction
,但在REMOVE
情况下,它会显示为所有行动,即Action
。
我缺少什么或理解错误? Flow应该从Actions
联合中删除正确的类型到if
和switch
内唯一可能的类型。
// @flow
const initialState = [];
type Item = { id: number, data: string };
type State = Item[];
type AddAction = {
type: 'ADD',
payload: Item
};
type RemoveAction = {
type: 'REMOVE',
payload: { id: number }
};
type ClearAction = {
type: 'CLEAR'
};
type Action = AddAction | RemoveAction | ClearAction;
const reducer: (State, Action) => State = (state = initialState, action) => {
switch (action.type) {
case 'ADD': {
return [...state, action.payload];
}
case 'REMOVE': {
return state.filter(t => t.id !== action.payload.id);
^ property `payload`. Property not found in
}
case 'CLEAR': {
return [];
}
default:
(action: empty);
return state;
}
};
export default reducer;
代码try flow
another try-flow repl我基本上做了同样的事情,打字推断按预期工作
答案 0 :(得分:3)
好的,似乎问题是在action
箭头函数中使用Array.filter
:
如果我用
替换REMOVE
案例内容
case 'REMOVE': {
const id = action.payload.id;
return state.filter(t => t.id !== id);
}
错误消失了。
我猜流量无法推断出箭头函数内的类型。知道原因会很有趣。
因此,flow使联合细化无效,因为它假定filter()可能对reducer参数action
(docs)产生副作用。在使用之前将操作或有效负载存储在const中。修复此问题。