刷類型體操時,問題的記錄及收穫
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
進行遍歷,即可實現。