此页内容

✔️ Tuple to Object

pengzhanbo

222字小于1分钟

2022-12-01

题目

Github: Tuple to Object

传入一个元组类型,将这个元组类型转换为对象类型,这个对象类型的键/值都是从元组中遍历出来。

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] 从数组中获取所有值,通过 映射类型,遍历 T[number] 中的值,并返回新的类型,其中 键 和 值 是 T[number] 的类型。

答案

type TupleToObject<T extends readonly PropertyKey[]> = {
  [P in T[number]]: P
}

参考