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

如何在TypeScript中实现Record的键值类型联合类型?

如何将对象类型转换为其所有属性值的联合类型?

你可以通过索引访问类型结合keyof操作符实现需求,直接定义如下类型别名:

type KeysTypeUnion<T> = T[keyof T];

原理说明

  • keyof T会提取类型T的所有键,组成对应的联合类型;
  • T[keyof T]用这个键的联合类型去索引T,最终得到所有属性值类型的联合,完全匹配你想要的效果。

示例验证

给定你提供的Foo类型:

type Foo = {
    key1: { bar: '1' };
    key2: { bar: '2' };
    key3: { bar: '3' };
}

type FooKeysUnion = KeysTypeUnion<Foo>;
// FooKeysUnion 等价于 { bar: '1' } | { bar: '2' } | { bar: '3' }

测试用例验证

  1. 基础值类型场景:
type Test1 = KeysTypeUnion<{ key1: '1'; key2: '2'; key3: '3' }>;
// Test1 等价于 '1' | '2' | '3'
  1. Record泛型场景:
type A = { a: number };
type B = { b: string };
type C = { c: boolean };

type Test2 = KeysTypeUnion<Record<string, A | B | C>>;
// Test2 等价于 A | B | C

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:52:45