类型体操-Tuple to Object
刷类型体操时,问题的记录及收获
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'}
思路
这是issues实现的思路
Given:
type TupleToObject<T extends readonly any[]> = any
First of all we need to get rid of any[]. Input array is readonly and has only strings as values. So we can use readonly string[] type (or ReadonlyArray<string>).
type TupleToObject<T extends readonly string[]> = any
Then we should transform array literal type (['tesla', 'model 3', 'model X', 'model Y'] as const) to object type. Mapped types to the rescue. We can iterate every value in array within mapped type using in keyword.
type TupleToObject<T extends readonly string[]> = {
[P in <somehow get T values>]: P
}
And to get the values we should use indexed access Array[number].
type TupleToObject<T extends readonly string[]> = {
[P in T[number]]: P
}
总结
这个问题我自己做的时候,就是卡在了不知道如何获取数组的元素类型(菜狗)。即 indexed-access。
通过这种方式可以获取数组元素的类型

以上加了as const,则认为是常量,拿到的是每个元素的类型
如果把as const去掉的话,则是这样的

拿到数组元素类型集合之后,再用 in 进行遍历,即可实现。

浙公网安备 33010602011771号