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

如何对可选属性的子元素使用indexed access type?

解决方案

你可以使用 TypeScript 内置的 NonNullable 工具类型先剔除可选属性自带的 undefined 类型,再进行索引访问即可:

type Person = {
  firstName: string;
  lastName: string;
  contact?: {
    type: string;
    value: string;
  }[];
};

// 先排除 undefined 再做索引访问
type Contact = NonNullable<Person['contact']>[number];

// 等价于 type Contact = { type: string; value: string }

原理说明

NonNullable<T> 是 TypeScript 内置的类型工具,作用是从联合类型 T 中移除所有 null 和 undefined 类型。经过它处理后的Person['contact'] 会从原本的 { type: string; value: string }[] | undefined 剔除 undefined 类型,只剩下纯数组类型,后续使用 [number] 索引访问就不会再触发类型报错了。

如果遇到更深层级的嵌套可选属性,逐层嵌套使用 NonNullable 处理对应层级的可选类型即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:45:03