typescript - 将 reducer 有效负载键入为对象类型或此类的数组
问题描述
我正在使用 useReducer 来维护对象类型数组的状态,并且我有一些操作类型。接口看起来像:
interface MyObject {
id: string;
foo: string;
bar: string;
}
interface Action {
type: 'add' | 'remove' | 'update';
payload?: Partial<MyObject>;
}
减速机功能:
const reducer = (current: MyObject[], action: Action): MyObject[] => {
switch (action.type) {
case 'add':
return [...current, createBaseMyObject()];
case 'remove':
return current.filter((item) => item.id !== action.payload?.id);
case 'update':
return current.map((item) => {
if (item.id === action.payload?.id) {
return { ...item, ...action.payload };
}
return item;
});
default:
return current;
}
};
这工作正常,但我还需要有条件地传递一个 MyObject 数组作为有效负载以批量更新。尝试将类型和功能更改为此:
interface ReducerAction {
type: 'add' | 'remove' | 'update';
payload?: Partial<MyObject> | MyObject[];
}
const reducer = (current: MyObject[], action: Action): MyObject[] => {
switch (action.type) {
case 'add':
return [...current, createBaseMyObject()];
case 'remove':
// Property 'id' does not exist on type 'MyObject[]'
return current.filter((item) => item.id !== action.payload?.id);
case 'update':
// With proper typing maybe this should be dedicated case
if (Array.isArray(action.payload)) {
return action.payload;
}
return current.map((item) => {
// Property 'id' does not exist on type 'MyObject[]'
if (item.id === action.payload?.id) {
return { ...item, ...action.payload };
}
return item;
});
default:
return current;
}
};
我试图避免断言或额外的运行时检查只是为了满足 TS。如果创建一个专用案例更容易,那很好。我只想尽可能最好地输入它,最好保持简单。想法?
解决方案
如果您希望 Typescript 了解某些类型具有特定的有效负载,那么您需要一个联合类型。我会将'update'
. 'replace'
数组有效负载似乎是一个更好的名称,因为您正在用该数组替换整个状态。
type Action = {
type: 'add';
// no payload
} | {
type: 'remove' | 'update';
// partial but with id required
payload: Partial<MyObject> & Pick<MyObject, 'id'>;
} | {
type: 'replace';
// array of objects
payload: MyObject[];
}
const reducer = (current: MyObject[], action: Action): MyObject[] => {
switch (action.type) {
case "add":
return [...current, createBaseMyObject()];
case "remove":
return current.filter((item) => item.id !== action.payload.id);
case "update":
return current.map((item) => {
if (item.id === action.payload.id) {
return { ...item, ...action.payload };
}
return item;
});
case "replace":
return action.payload;
default:
return current;
}
};
推荐阅读
- ssl - 从启用 SSL 的远程服务器连接到 cassandra cqlsh
- php - 如果在新类别中,则显示新徽章 Woocommerce
- powershell - Compare-Object PowerShell 输出一个 1KB 的文件,其中包含 2 个空行
- javascript - Cheerio - 查找并打印与查询匹配的所有属性
- python - 在关闭对话框之前添加验证
- python - Python 乌龟井字游戏
- python - 如何计算结果发生了多少次?
- javascript - 如何为 Redux 中的一组组合 reducer 制定规则?
- linux - 如何正确配置 Beaglebone Black PWM
- ethernet - 如何在 Rockwell ControlLogix 上进行故障排除和减少通信开销