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

TypeScript中使用括号表示法访问对象深层可选属性报错解决

为什么会报这个错?

因为你的supplierInvoiceListPaginated属性是**可选(带?)且可能为null**的,TypeScript解析SupplierInvoiceListPaginatedQuery["supplierInvoiceListPaginated"]得到的类型是:

{ total?: number | null; pageInfo: {...}; edges?: ... } | null | undefined

当你试图直接访问["edges"]时,TypeScript会考虑到null和undefined的情况——这两个类型上根本没有edges属性,所以抛出错误。

怎么解决?

根据你的场景,有几种可行的方式:

1. 类型层面确保父属性非空(适合定义类型变量时)

用TypeScript内置的NonNullable工具类型,把null和undefined从父属性的类型中排除,这样就能安全访问edges:

let supplierInvoiceList: NonNullable<SupplierInvoiceListPaginatedQuery["supplierInvoiceListPaginated"]>["edges"]

2. 运行时检查收窄类型(适合处理实际数据时)

如果是拿到查询结果后要访问edges,先通过条件判断确保supplierInvoiceListPaginated存在,TypeScript会自动收窄类型:

// 假设这是你的查询返回数据
const queryResult: SupplierInvoiceListPaginatedQuery = await fetchData();

if (queryResult.supplierInvoiceListPaginated) {
  // 这里TypeScript知道supplierInvoiceListPaginated一定存在,能安全访问edges
  const edges = queryResult.supplierInvoiceListPaginated.edges;
}

3. 非空断言(确定父属性一定存在时用)

如果你能100%保证supplierInvoiceListPaginated不会是null或undefined,可以用非空断言操作符!(注意:滥用可能导致运行时错误):

// 运行时访问时用!断言
const edges = queryResult.supplierInvoiceListPaginated!.edges;

// 类型定义时不能直接用!,得用NonNullable,这就是你之前尝试失败的原因

内容的提问来源于stack exchange,提问作者Julien Lemaître

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:42:37