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

React+TypeScript中reducer变量访问报错?提示loading不存在于object类型

问题原因分析

报错Property 'loading' does not exist on type 'object'的核心原因是TypeScript的类型约束不明确:

  • 你给reducer函数的返回值显式标注了object类型,这个类型在TS里是最宽泛的通用对象类型,不包含任何具体属性的定义。TypeScript无法从这个类型中推断出loading属性的存在,所以访问itemList.loading时会触发报错。
  • 虽然你定义了带有loading属性的initialState,但reducer的返回类型object覆盖了TS对初始状态的自动类型推断,导致itemList的类型被限定为无具体属性的object,而非包含loading的具体对象。

修复方案

推荐定义明确的状态类型来解决这个问题,代码示例如下:

import { useReducer } from "react";

// 定义状态的具体类型接口
interface AppState {
  loading: boolean;
  // 后续添加的状态属性都可以在这里声明
}

// 使用定义好的类型约束reducer的参数和返回值
const reducer = (state: AppState, action: any): AppState => {
    const result = { ...state };
    // ...你的业务逻辑
    return result;
}

// 用接口约束初始状态
const initialState: AppState = { loading: true };

export default function TestWebRTC() {
    const [itemList, updateItemList] = useReducer(reducer, initialState);
    return (
        <div>
            {itemList.loading}
        </div>
    )
}

也可以让TypeScript自动推断类型,去掉reducer的返回类型标注,同时用typeof initialState约束state参数:

const reducer = (state: typeof initialState, action: any) => {
    const result = { ...state };
    // ...你的业务逻辑
    return result;
}

内容的提问来源于stack exchange,提问作者The KNVB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:35:00