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

如何从Redux的Reducer中自动推导获取组合State的类型

实现方案

你之前的写法得到的是「reducer配置对象的类型」,每个属性都是Reducer函数类型,和实际的State结构(每个属性是对应切片的状态值)完全不匹配,所以会报类型不兼容错误。


方案1:手动构造工具类型提取

首先定义提取单个Reducer状态的工具类型:

import type { Reducer } from "redux";

// 工具类型:从Reducer类型中提取出状态的类型
type ExtractReducerState<T> = T extends Reducer<infer StateType, any> ? StateType : never;

基于你的reducer配置对象生成完整的RootState类型:

// 自动生成组合后的根状态类型,新增/修改/删除reducer切片时会自动同步
type RootState = {
  [Key in keyof typeof reducer]: ExtractReducerState<typeof reducer[Key]>
};

如果要单独获取某个切片的类型,直接索引访问即可:

type SelectedElementType = RootState["selectedElement"]; // 等价于StructureElement
type FetchedStateType = RootState["fetchedState"]; // 等价于FetchedState

方案2:基于combineReducers直接生成(更优)

如果你的reducer对象是传给combineReducers的配置,用Redux官方推荐的标准写法即可,不需要自己写工具类型:

import { combineReducers } from "redux";

const rootReducer = combineReducers(reducer);
// 直接从根reducer的返回值提取类型,完全自动同步
type RootState = ReturnType<typeof rootReducer>;

如果使用Redux Toolkit的configureStore初始化store,还可以直接从store实例提取RootState,写法更简洁:

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

const store = configureStore({ reducer });
type RootState = ReturnType<typeof store.getState>;

Mock数据使用示例

直接用生成的RootState类型约束Mock数据,类型不匹配会自动报错:

const mockState: RootState = {
  selectedElement: {
    // 编辑器会自动提示StructureElement的所有属性,字段写错/类型不对都会触发TS报错
  },
  fetchedState: {
    // 自动提示FetchedState的属性
  },
  // 其他切片字段
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:24:04