带有 preloadedState 的 Redux (Toolkit) 存储的类型定义

Type definitions for Redux (Toolkit) store with preloadedState

我正在尝试让输入工作来配置具有预加载状态的 Redux 存储。

Redux Toolkit TypeScript quick start guide有这个例子:

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 的状态

您可以根据 reducer 的参数类型推断状态的类型。我们希望将 reducer 值分离到一个单独的 const 中,以便仅在减速器上使用 typeof

const reducer = {
  one: oneSlice.reducer,
  two: twoSlice.reducer
};

您使用的是 slice reducer 的对象,而不是创建的函数 combineReducers。 Redux 工具包导出了一个实用程序类型,我们可以使用它来从 reducer map 对象表示法推断状态。

import { StateFromReducersMapObject } from "@reduxjs/toolkit";

export type RootState = StateFromReducersMapObject<typeof reducer>

Return 类型

我们也可以通过查看 initStoreReturnType 获得 Store 的类型,然后通过查看 RootState 获得 RootState =19=] 来自商店的 getState 方法。那将是与示例最相似的。同样的方法还允许我们获取 AppDispatch 的类型。请注意,我们使用括号表示法而不是点表示法,因为我们的 Storetype,而不是 object.

type Store = ReturnType<typeof initStore>
type RootState = ReturnType<Store['getState']>
type AppDispatch = Store['dispatch']

预加载状态类型

reducerinitStore 分开的好处是我们现在可以使用 reducer 中的类型来为 preloadedState 参数声明适当的类型,这不是之前输入过。

import { configureStore, Slice, StateFromReducersMapObject, PreloadedState } from "@reduxjs/toolkit";

const reducer = {
  one: oneSlice.reducer,
  two: twoSlice.reducer
};

export type RootState = StateFromReducersMapObject<typeof reducer>

export function initStore(preloadedState?: PreloadedState<RootState>) {
  return configureStore({
    reducer,
    preloadedState,
  });
}

type Store = ReturnType<typeof initStore>

export type AppDispatch = Store['dispatch']

Typescript Playground Link