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

如何获取TypeScript可选嵌套对象中属性的类型?

解决TypeScript可选属性嵌套类型获取问题

问题出在MyType里的a是可选属性,所以MyType['a']的实际类型是{ b: number } | undefined。直接访问['b']时,undefined类型没有b属性,TypeScript会抛出类型错误。

你可以通过以下两种方式正确获取b的类型:

方法1:用NonNullable排除undefined

NonNullable工具类型会移除类型中的null和undefined,确保我们访问的是存在的a属性:

type MyType = {
  a?: {
     b: number;
  }
}

type AnotherType = {
  mytype: NonNullable<MyType['a']>['b'] // 类型为number
}

方法2:提取a的非可选类型

通过Extract工具类型从MyType['a']中筛选出对象类型的部分,再访问b属性:

type MyType = {
  a?: {
     b: number;
  }
}

type AType = Extract<MyType['a'], object>
type AnotherType = {
  mytype: AType['b'] // 类型为number
}

两种方法都能正确得到b的number类型,第一种写法更简洁直观,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:02:34