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

TS报错Property 'item' does not exist on type 'object'如何修复

报错原因

错误Property 'item' does not exist on type 'object'的根源是类型定义不准确:你将HeroList接口中items字段标注为object[]类型,TS的通用object类型仅表示值为引用类型对象,不包含任何自定义属性的声明,因此访问el.item时,TS无法确认泛化的object上存在item属性,直接抛出类型错误。同时你的addItem reducer的入参类型也定义过于宽泛,和实际存入的数据结构不匹配。

修复方案
  • 提取items数组单条元素的明确类型,避免使用无结构的通用object类型标注结构化数据
  • 替换HeroList接口中items字段的类型为明确的元素结构数组
  • 修正addItem action的Payload类型,和实际存入的数据结构保持一致

修正后的类型定义与slice代码如下:

// 定义items数组存储的单条英雄元素结构
interface HeroItem {
  id: string | undefined;
  item: string;
}

interface HeroList {
  // 替换原有的object[]为明确结构的数组类型
  items: HeroItem[];
  // elements结构和HeroItem完全一致,可直接复用类型
  elements: HeroItem;
}

const initialState: HeroList = {
  items: [],
  elements: {
    id:'',
    item:'',
  }
}

export const heroListSlice = createSlice({
  name: 'heroList',
  initialState,
  reducers: {
    // 修正payload类型为明确的HeroItem,替换原宽泛的Object类型
    addItem: (state, action: PayloadAction<HeroItem>) => {
      state.items.push(action.payload)
      localStorage.setItem('items', JSON.stringify(state.items));
    },
  },
})

修改完成后,TS会自动推导heroArray.find()中回调参数el的类型为HeroItem,可以正常识别el.item属性,报错消失。

注意:日常开发中不要使用object/Object这类宽泛类型标注有明确结构的对象,会丢失TS的类型校验能力,极易出现属性访问、参数传递相关的类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 06:06:48