Redux Toolkit+TypeScript开发中Store内Reducer报错求助
问题分析与解决方案
核心错误原因
你的Reducer存在两个返回类型不匹配的问题,导致TypeScript类型检查失败:
- ADD_ARTICLE分支:返回的对象额外添加了
newArticle属性,不符合ArticleState的结构要求(ArticleState仅包含articles数组)。 - 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
额外优化建议(可选)
- 收紧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
- Store键名语义化:创建Store时,将reducer的键名改为更清晰的名称(比如
articles):
export const store = configureStore({ reducer: { articles: reducer, } });
- 修正DispatchType:由于使用了Redux Thunk,你的
DispatchType需要支持接收函数类型,否则thunk无法正常工作:
import { Dispatch } from 'redux' type DispatchType = Dispatch<ArticleAction>
内容的提问来源于stack exchange,提问作者Salar Sali
相关产品推荐
相关产品推荐

