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

TypeScript使用Object.keys()时报Object is possibly undefined问题问询

报错根因

TypeScript 不会主动关联Object.keys(people)返回的 key 和people的索引关系,哪怕 key 是从people遍历出来的,通过people[id]索引取值时,TS 依然会判定返回值可能为undefined,这是索引签名类型的默认行为。


推荐修复方案(无需非空断言)

方案1:使用Object.entries遍历(最简便)

直接在遍历阶段同时拿到 key 和对应的有效值,不需要二次索引取值,从根源避免类型问题。

{people && Object.entries(people).map(([id, peopleItem]) => (
  <PeopleCard
    location={peopleItem}
    onDelete={() => openDeletePeopleModal(locations[id])}
    onEdit={() => openEditPeopleDrawer(locations[id])}
    onClick={() => history.push(`/todo/${todo.id}/people/${peopleItem.id}`)}
  />
))}

Object.entries(people)返回的每个元素是[string, People]类型的元组,peopleItem的类型天然是确定的People,不会触发空值报错。

方案2:对索引取值做类型收窄

如果必须保留Object.keys的写法,可以在取值后加一次空值判断,不符合条件的项直接跳过渲染:

{people && Object.keys(people).map((id: string) => {
  const peopleItem = people[id]
  if (!peopleItem) return null
  return (
    <PeopleCard
      location={peopleItem}
      onDelete={() => openDeletePeopleModal(locations[id])}
      onEdit={() => openEditPeopleDrawer(locations[id])}
      onClick={() => history.push(`/todo/${todo.id}/people/${peopleItem.id}`)}
    />
  )
})}

补充说明

你代码描述里提到people的类型为{ [id: string]: Location } | undefined,但你贴的类型定义中ITodo.people的类型是{ [id: string]: People },如果是笔误请对齐类型,避免额外的类型报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:45:10