如何用TypeScript工具类型将两个元组转为对应键值对对象?
问题
我有两个只读元组:
const tuples1 = ['a', 'b', 'c'] as const; const tuples2 = [1, 2, 3] as const;
想要生成一个按索引位置映射的对象:
const ResultMerge = { 'a': 1, 'b': 2, 'c': 3 }
尝试了两个工具类型:
type TuplesToObject<T extends readonly any[], U extends readonly any[]> = { [K in T[number]]: U[Extract<keyof T, K>[number]] }
type TupleToObject<T extends readonly string[], U extends readonly any[]> = Record<T[number], U[Extract<keyof T, number>]>
但结果都是每个键对应第二个元组所有值的联合类型:
{ a: 3 | 1 | 2, b: 3 | 1 | 2, c: 3 | 1 | 2 }
需要实现正确的索引映射,让每个键对应第二个元组同位置的值。
解决方案
要实现按索引关联两个元组的元素,需要借助元组的数字索引来同时定位两个元组的对应位置,工具类型写法如下:
type TuplesToObject<T extends readonly PropertyKey[], U extends readonly any[]> = { [I in keyof T as T[I]]: U[I] };
代码说明
keyof T获取元组的数字索引(比如0、1、2)as T[I]将索引转换为第一个元组对应位置的元素,作为对象的键U[I]取第二个元组对应索引位置的值,作为对象的键对应值
验证示例
const tuples1 = ['a', 'b', 'c'] as const; const tuples2 = [1, 2, 3] as const; type Result = TuplesToObject<typeof tuples1, typeof tuples2>; // 最终结果:{ a: 1; b: 2; c: 3 }
原写法问题分析
- 原代码直接遍历第一个元组的元素(
[K in T[number]]),无法关联到元素对应的索引位置 Extract<keyof T, K>逻辑不成立:K是字符串类型的元组元素(比如'a'),而keyof T是数字索引,提取结果为空,导致U[...]只能匹配到第二个元组的所有值,形成联合类型
内容的提问来源于stack exchange,提问作者Nikoh
相关产品推荐
相关产品推荐

