带有preloadedState的Redux(Toolkit)存储的类型定义
我正在尝试使用类型来配置具有预加载状态的 Redux 存储。
在终极版工具包打字稿快速入门指南有这个例子:
import { configureStore } from '@reduxjs/toolkit'
const store = configureStore({
reducer: {
one: oneSlice.reducer,
two: twoSlice.reducer
}
})
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
不幸的是,在预加载状态下,它看起来更像这样:
export function initStore(preloadedState) {
const store = configureStore({
reducer: {
one: oneSlice.reducer,
two: twoSlice.reducer
},
preloadedState,
})
return store
}
我现在从哪里获得RootState类型和AppDispatch类型?
回答
来自减速器的状态
您可以根据减速器的参数类型推断您的状态类型。我们希望将reducer值分离成一个单独的值const,以便typeof仅在减速器上使用。
const reducer = {
one: oneSlice.reducer,
two: twoSlice.reducer
};
您正在使用切片减速器的对象而不是创建的函数combineReducers。Redux 工具包导出一个实用程序类型,我们可以使用它来从 reducer 映射对象表示法推断状态。
import { ReducerFromReducersMapObject } from "@reduxjs/toolkit";
export type RootState = StateFromReducersMapObject<typeof reducer>
返回类型
我们也可以Store通过查看ReturnTypeof获得 the 的类型initStore,然后RootState通过查看ReturnType来自 store 的getState方法获得 the 。这将与示例最相似。同样的方法还允许我们获取AppDispatch. 请注意,我们使用括号表示法而不是点表示法,因为我们Store是 a type,而不是 an object。
type Store = ReturnType<typeof initStore>
type RootState = ReturnType<Store['getState']>
type AppDispatch = Store['dispatch']
预加载状态类型
分离reducer外部的好处initStore是我们现在可以使用来自reducer的类型来为preloadedState参数声明适当的类型,这是之前没有类型化的。
import { configureStore, Slice, StateFromReducersMapObject, DeepPartial } from "@reduxjs/toolkit";
const reducer = {
one: oneSlice.reducer,
two: twoSlice.reducer
};
export type RootState = StateFromReducersMapObject<typeof reducer>
export function initStore(preloadedState?: DeepPartial<RootState>) {
return configureStore({
reducer,
preloadedState,
});
}
type Store = ReturnType<typeof initStore>
export type AppDispatch = Store['dispatch']
打字稿游乐场链接
THE END
二维码