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

如何访问TypeScript中的可空嵌套类型?

解决TypeScript嵌套可选字段的类型提取问题

因为b是可选字段,它的类型是{ c: string } | undefined,直接链式访问['c']时TS会报错——毕竟undefined上不存在c属性。以下是几种可行的解决方法:

方法一:用NonNullable排除undefined类型

直接过滤掉undefined分支后,再提取目标类型:

type Query = { a: { b?: { c: string } } };

type CType = NonNullable<Query['a']['b']>['c']; // 最终类型为string

方法二:条件类型推断

通过条件类型配合infer直接提取c的类型:

type Query = { a: { b?: { c: string } } };

type CType = Query['a']['b'] extends { c: infer U } ? U : never; // string

方法三:通用深层类型提取工具

如果需要频繁提取不同深层路径的类型,可以写一个通用工具类型,支持用字符串路径解析:

type DeepPick<T, Path extends string> = 
  Path extends `${infer Key}.${infer Rest}`
    ? Key extends keyof T
      ? DeepPick<T[Key], Rest>
      : never
    : Path extends keyof T
      ? T[Path]
      : never;

// 使用示例
type Query = { a: { b?: { c: string } } };
type CType = DeepPick<Query, 'a.b.c'>; // string

这个工具类型会递归解析路径字符串,自动处理可选字段的undefined分支,最终返回有效类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:35:27