如何对可选属性的子元素使用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
相关产品推荐
相关产品推荐

