我在从flow docs开始基本上执行基本的redux-reducer示例时遇到了流错误 .
此处添加到代码中的流出错:在 REMOVE
开关情况下: action
未解析为正确的类型 .
如果我将鼠标悬停在vscode中的 payload
上,则在 ADD
情况下将其显示为 AddAction
,但在 REMOVE
情况下,它显示为所有操作的并集,即 Action
.
我错过了什么或理解错了什么? Flow应该从 Actions
union中删除正确的类型到 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;
169994
-
代码
-
another try-flow repl我在哪里做了基本相同的事情,并打字推断按预期工作
1 回答
好吧,似乎问题是使用了
action
里面Array.filter
箭头功能:如果我用
REMOVE
案例内容替换错误消失了 .
我猜流量无法推断出箭头函数内的类型 . 知道原因会很有趣 .
编辑:related question
因此,flow使联合细化无效,因为它假定filter()可能对reducer参数
action
(docs)执行副作用 . 在使用之前将操作或有效负载存储在const中 .