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

如何在TypeScript中获取对象所有键值对组成的联合类型

解决方案

你可以通过构造映射类型,在遍历对象键的时候直接生成仅包含当前键的单键对象,再取所有值的联合即可实现需求,通用实现如下:

type ObjectToKeyValueUnion<T> = {
  [K in keyof T]: { [P in K]: T[K] }
}[keyof T]

实际使用

针对你给出的PersonInfo类型,直接传入工具类型即可得到目标联合:

type PersonInfo = {
  id: number;
  name: string;
  address: {
    street: string;
    country: string;
  }
}

type TargetUnion = ObjectToKeyValueUnion<PersonInfo>
// 推导结果为:{ id: number } | { name: string } | { address: { street: string; country: string; } }

如果你需要直接从person常量推导类型,也可以直接传入typeof person:

const person = {
  id: 87,
  name: 'Some Name',
  address: {
    street: 'Some street',
    country: 'Some country'
  }
}

type TargetUnionFromConst = ObjectToKeyValueUnion<typeof person>

原写法问题说明

你之前写的PersonTest1只取到了所有属性值的联合,缺少了包裹属性的单键对象结构。新写法在映射阶段就为每个键单独构造了符合要求的单键对象,再取联合就刚好匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:15:00