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

联合类型的条件索引:获取仅存在于部分类型的属性类型

从联合类型中获取仅存在于部分类型的属性类型

问题场景

当我们有一个联合类型,想要访问其中仅部分成员拥有的属性时,直接索引会报错,比如:

type A = {
    one: 'a' | 'b'
}

type B = {
    two: 'c' | 'd'
}

type Both = A | B;

// 直接索引会报错:Property 'two' does not exist on type 'Both'
// type X = Both['two'];
// 预期结果: 'c' | 'd' | undefined

解决方案

可以通过条件类型结合类型推断实现一个通用工具类型,来处理这种场景:

type GetUnionProp<T, K extends PropertyKey> = T extends { [P in K]: infer V } 
  ? V 
  : undefined;

工具类型说明

  • 遍历联合类型T的每个成员,检查该成员是否包含属性K
  • 如果包含,用infer V提取该属性的类型V
  • 如果不包含,返回undefined

使用示例

把上面的场景代入:

type A = {
    one: 'a' | 'b'
}

type B = {
    two: 'c' | 'd'
}

type Both = A | B;

type X = GetUnionProp<Both, 'two'>;
// 结果:'c' | 'd' | undefined

这样就能得到预期的类型结果,既包含存在该属性的类型对应的属性值,也补上了不存在该属性时的undefined类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:15:11