You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用preloadedState时如何生成Redux Toolkit TypeScript的AppDispatch类型

解决方案

直接提取工厂函数createStore的返回值类型,间接获取AppDispatch类型即可,无需依赖实际实例化的store对象,修改后的代码如下:

export const rootInitialState: Pick<RootState, 'home'> = {
  home: homeInitialState,
};

const reducer = combineReducers({
  home: homeReducer,
  [homeApi.reducerPath]: homeApi.reducer,
});

export type RootState = ReturnType<typeof reducer>;

// 修复后的AppDispatch类型定义
export type AppDispatch = ReturnType<typeof createStore>['dispatch'];

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

export const createStore = (preloadedState: Partial<RootState>) => configureStore({
  reducer,
  preloadedState,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(
    homeApi.middleware,
  ),
});
实现原理

configureStore的返回类型仅由传入的reducer、middleware配置决定,和运行时传入的preloadedState参数无关。createStore作为返回store实例的工厂函数,它的返回类型在你写完配置的时候就已经固定,通过ReturnType<typeof createStore>就能拿到store的类型,再通过索引访问['dispatch']即可提取到和直接实例化store完全一致的AppDispatch类型。
这个方案是完全类型安全的,后续新增reducer、修改middleware配置时,AppDispatch会自动同步更新,不需要手动修改类型定义。

内容的提问来源于stack exchange,提问作者Drew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:09:03