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

Redux Toolkit+TypeScript开发中Store内Reducer报错求助

问题分析与解决方案

核心错误原因

你的Reducer存在两个返回类型不匹配的问题,导致TypeScript类型检查失败:

  1. ADD_ARTICLE分支:返回的对象额外添加了newArticle属性,不符合ArticleState的结构要求(ArticleState仅包含articles数组)。
  2. REMOVE_ARTICLE分支:直接返回了过滤后的IArticle[]数组,而没有包裹成ArticleState类型的对象(缺少articles键)。

修复后的Reducer代码

import * as actionTypes from "./actionTypes"

const initialState: ArticleState = {
  articles: []
}
let lastID = 0

const reducer = (state: ArticleState = initialState, action: ArticleAction) => {
  switch(action.type){
    case actionTypes.ADD_ARTICLE:
      const newArticle: IArticle = {
        id: ++lastID,
        title: action.article.title,
        body: action.article.body
      }
      // 正确更新articles数组,而非添加额外属性
      return { 
        ...state, 
        articles: [...state.articles, newArticle] 
      }
    
    case actionTypes.REMOVE_ARTICLE:
      // 将过滤后的数组包裹成ArticleState结构返回
      return {
        ...state,
        articles: state.articles.filter(article => article.id !== action.article.id)
      }
    default: 
      return state
  }
}

export default reducer

额外优化建议(可选)

  1. 收紧Action类型:将ArticleAction改为联合类型,让TypeScript能更精准地推断Action结构:
type AddArticleAction = {
  type: typeof actionTypes.ADD_ARTICLE,
  article: IArticle
}

type RemoveArticleAction = {
  type: typeof actionTypes.REMOVE_ARTICLE,
  article: IArticle
}

type ArticleAction = AddArticleAction | RemoveArticleAction
  1. Store键名语义化:创建Store时,将reducer的键名改为更清晰的名称(比如articles):
export const store = configureStore({
  reducer: {
    articles: reducer,
  }
});
  1. 修正DispatchType:由于使用了Redux Thunk,你的DispatchType需要支持接收函数类型,否则thunk无法正常工作:
import { Dispatch } from 'redux'
type DispatchType = Dispatch<ArticleAction>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:05:20