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

如何从含可选属性的TypeScript嵌套类型中提取指定子类型?

从嵌套可选属性的TypeScript类型中提取子类型

已知TypeScript类型Something,其中a和foo均为可选属性:

type Something = {
  a?: {
    foo?: {
      bar: {
        c: {
          id: string,
          countryCode: number,
          animal: { /* 具体类型定义 */ }
        }
      }
    }
  }
}

需要创建类型MyType,使其等价于Something中嵌套的bar类型,即:

type MyType = {
  c: {
    id: string,
    countryCode: number,
    animal: { /* 具体类型定义 */ }
  }
}

解决方案

可以通过索引访问类型结合NonNullable工具类型提取目标子类型,具体实现如下:

type MyType = NonNullable<NonNullable<Something['a']>['foo']>['bar'];

代码说明:

  • Something['a']:获取a属性的类型,结果为{ foo?: { bar: ... } } | undefined
  • NonNullable<Something['a']>:排除undefined,得到{ foo?: { bar: ... } }
  • NonNullable<...>['foo']:获取foo属性的类型,结果为{ bar: ... } | undefined
  • 再次使用NonNullable排除undefined后,通过['bar']即可拿到最终的bar类型

如果你的TypeScript版本在4.9及以上,还可以使用更简洁的可选链风格索引访问:

type MyType = NonNullable<Something['a']?.['foo']?.['bar']>;

内容的提问来源于stack exchange,提问作者I am X

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:10:14