13 元组转换为对象
约 328 字大约 1 分钟
2025-07-07
题目
将一个元组类型转换为对象类型,这个对象类型的键/值和元组中的元素对应。
例如:
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
type result = TupleToObject<typeof tuple> // expected { 'tesla': 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}
解法
考虑使用T[number]
提取出元组中的所有元素组成联合类型,例如:
const tuple = ['a', 'b', 'c'] as const
// typeof tuple = readonly ['a', 'b', 'c']
type T = typeof tuple
// T[number] => 'a' | 'b' | 'c'
这里as const
的作用是将tuple
的类型固定为字面量联合类型['a', 'b', 'c']
,否则会被推断为string[]
。
得到元素联合类型后进行遍历,就有:
type TupleToObject<T extends readonly any[]> = {
K in T[number]: K
}
报错。这是因为要生成键的话,需要使用[]
包裹K in T[number]
,即[K in T[number]]
。
[]
是映射类型语法的一部分,表示要用联合类型中的每个成员作为键名。
于是:
type TupleToObject<T extends readonly any[]> = {
[K in T[number]]: K
}
但是依然存在报错,这是由于映射类型中的key
只能是string``number``symbol
三种基本类型,因此要对类型参数T
加以约束:
type TupleToObject<T extends readonly (string | symbol | number)[]> = {
[K in T[number]]: K
}