TypeScript React中含对象数组接口的useReducer报ts2769错如何解决?
报错原因
该TS2769报错的核心是TypeScript无法正确匹配useReducer的类型重载,根源有两个:
- 初始状态
initialState里的users是空数组,没有显式指定类型,被TS自动推断为never[],和reducer后续返回的用户数组类型不匹配 - 你后续定义的
USER_STATE接口中users: [User]是长度固定为1的元组类型,不符合你需要的任意长度用户数组的需求
修复步骤
- 修正状态接口定义,将
users的类型改为User[](任意长度的User类型数组) - 为
initialState显式绑定USER_STATE类型,避免TS将空数组推断为never[] - 为reducer函数显式标注返回值类型为
USER_STATE,确保类型匹配
完整修复后代码
import React, {useReducer} from 'react' type ACTION_TYPE = | {type: 'SET_USER', userId: number} | {type: 'DELETE_USER', userId: number, deleteMessages: boolean} interface User { id : number; name? : string; surname?: string; hasDiscount?: boolean; } // 修正状态接口:users为User类型数组 interface USER_STATE { users: User[] } // 显式指定reducer的入参和返回值类型 const myReducer = (state : USER_STATE, action : ACTION_TYPE): USER_STATE => { switch (action.type) { case 'DELETE_USER': return {users: [...state.users, {id: action.userId}]} default: return state; } } // 为初始状态绑定类型 const initialState: USER_STATE = { users : [] } const TestingComponent : React.FC = () => { const [state, dispatch] = useReducer(myReducer,initialState) return <div></div> } export default TestingComponent
内容的提问来源于stack exchange,提问作者Alk
相关产品推荐
相关产品推荐

