TypeScript:在使用';展开结果';Redux工具包的开发
我正在努力为AsyncThunkAction的返回类型找到合适的类型,以便与Redux Toolkit的unwrapResult方法一起使用(请参阅:): 片中异步thunk的声明:TypeScript:在使用';展开结果';Redux工具包的开发,typescript,redux,redux-toolkit,Typescript,Redux,Redux Toolkit,我正在努力为AsyncThunkAction的返回类型找到合适的类型,以便与Redux Toolkit的unwrapResult方法一起使用(请参阅:): 片中异步thunk的声明: 导出 const createChannel=createAsyncThunk< {id:string}, ChannelReqDto, 注射型 >(“通道/创建通道”,异步(请求,thunkApi)=>{ const result=wait thunkApi.extra.client.post( `/store/
导出
const createChannel=createAsyncThunk<
{id:string},
ChannelReqDto,
注射型
>(“通道/创建通道”,异步(请求,thunkApi)=>{
const result=wait thunkApi.extra.client.post(
`/store/${req.storeId}/channels`,
{
类别:请求类别,
组:请求组,
名称:req.name,
规则:[],
}
);
返回结果数据;
});
React组件中的用法:
const newChannel=等待调度(
创建频道({
姓名:姓名,,
组:组,,
类别:类别,,
storeId:storeIdParam,
规则:[],
})
);
常量结果=展开结果(新通道);
类型脚本错误:
TS2345: Argument of type 'AsyncThunkAction<{ id: string; }, ChannelReqDto, InjectedAxiosClientType>' is not assignable to parameter of type 'UnwrappableAction'. Property 'payload' is missing in type 'AsyncThunkAction<{ id: string; }, ChannelReqDto, InjectedAxiosClientType>' but required in type 'UnwrappableAction'.
@acemarke在Reactiflux聊天中给了我答案: 我必须使用redux存储中声明的类型分派(在我的案例store.tsx中):
export type AppDispatch=typeof store.dispatch;
export const useAppDispatch=()=>useAppDispatch();
- 默认情况下,store.dispatch()返回传入的操作
- 中间件可以修改返回值并替换为其他内容
- thunk中间件通过返回thunk函数返回的任何内容来实现这一点
- 基本分派类型不知道安装了thunk中间件,因此它认为它将返回您传入的任何内容—在本例中,是thunk函数本身
- thunk函数肯定不是“不可破解的”,也没有有效载荷字段
- 切换到定制的AppDispatch类型意味着TS现在可以识别“dispatch的返回类型是thunk函数返回的内容”