類型體操-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 進行遍歷,即可實現。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章