Redux Toolkit配置createAsyncThunk显式泛型后upsertMany报类型错误
Redux Toolkit 异步Thunk结合Entity Adapter的类型报错问题
在使用Redux Toolkit开发通知模块时,遇到如下类型异常:
传入Notifications类型单值时,notificationsAdapter.upsertMany()抛出类型不匹配错误,提示该类型无法赋值给要求的Notifications[] | Record<EntityId, Notifications>集合类型参数。
触发报错的实现代码
export const fetchNotifications = createAsyncThunk< Notifications, void, { state: RootState } >("notifications/fetchNotifications", async (_, { getState }) => { const allNotifications = selectAllNotifications(getState()); const [latestNotification] = allNotifications; const latestTimestamp = latestNotification ? latestNotification.date : ""; const response = await client.get( `/fakeApi/notifications?since=${latestTimestamp}` ); return response.notifications; }); const notificationsSlice = createSlice({ name: "notifications", initialState, reducers: { allNotificationsRead(state) { Object.values(state.entities).forEach((notification) => { notification && (notification.read = true); }); }, }, extraReducers: (builder) => { builder.addCase(fetchNotifications.pending, (state) => { state.status = "loading"; }); builder.addCase(fetchNotifications.rejected, (state, action) => { state.status = "failed"; state.error = action.error.message as Error; }); builder.addCase(fetchNotifications.fulfilled, (state, action) => { state.status = "succeeded"; Object.values(state.entities).forEach((notification) => { notification && (notification.isNew = !notification.read); }); notificationsAdapter.upsertMany(state, action.payload); }); }, });
异常复现的配置细节
- 代码中为
createAsyncThunk显式指定了全量泛型参数,依次为:异步逻辑返回值类型Notifications、thunk入参类型void、自定义ThunkApiConfig配置(其中state字段指定为全局根状态类型RootState,该RootState由store实例自动推导生成,定义格式为export type RootState = ReturnType<typeof store.getState>) - 临时规避报错的方案:移除
createAsyncThunk上的所有显式泛型标注,在异步逻辑内部手动将getState()的返回值断言为RootState类型时,上述upsertMany的类型报错会完全消失 - 当前待排查问题:无法定位显式配置的泛型参数中,哪一项导致了
fulfilledaction的payload类型推导异常,最终引发Entity Adapter方法的类型匹配错误。
内容的提问来源于stack exchange,提问作者yudhiesh
相关产品推荐
相关产品推荐

