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

TypeScript React中含对象数组接口的useReducer报ts2769错如何解决?

报错原因

该TS2769报错的核心是TypeScript无法正确匹配useReducer的类型重载,根源有两个:

  • 初始状态initialState里的users是空数组,没有显式指定类型,被TS自动推断为never[],和reducer后续返回的用户数组类型不匹配
  • 你后续定义的USER_STATE接口中users: [User]是长度固定为1的元组类型,不符合你需要的任意长度用户数组的需求
修复步骤
  1. 修正状态接口定义,将users的类型改为User[](任意长度的User类型数组)
  2. 为initialState显式绑定USER_STATE类型,避免TS将空数组推断为never[]
  3. 为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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:57:02