使用typescript限制具有操作名称的负载类型



我正在使用React的useReducer,并且我正在尝试使用typescript来实现当操作类型为"SET"时,操作负载必须是数组,而操作类型是"ADD"时,负载必须是对象。

像这样的东西:

type TItemsAction = TActionItemsSet & TActionItemsAdd;
type TActionItemsSet = {
type: 'SET';
payload: TItem[];  // update the whole item array with new array
};
type TActionItemsAdd = {
type: 'ADD';
payload: TItem;  // add one new item object to item array
};
function itemsReducer(state: TItem[], action: TItemsAction) {
switch (action.type) {
case 'SET': {
return action.payload;
}
case 'ADD': {
return [...state, action.payload];
}
default: {
throw new Error(`Unsupported action type: ${action.type}`);
}
}
}
const [items, dispatch] = useReducer(itemsReducer, []);

我收到打字抱怨:交叉点"TItemsAction"已减少为"never",因为属性"type"在某些组成部分中具有冲突的类型

有办法做到这一点吗?

看起来是一个或另一个,而不是一次两个

type TItemsAction = TActionItemsSet | TActionItemsAdd;

最新更新