李恒道 发表于 2022-7-18 10:18:00

typescript类型体操记录贴(四)Tuple to Object

```
Give an array, transform into an object type and the key/value must in the given array.

For example:
```
给一个数组,转化为对象,key和value必须在给定的数组中
例如
```
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'}
```
['tesla', 'model 3', 'model X', 'model Y'] as const
通过使用as const推断了一个元组类型
我们期待   
```
TupleToObject<typeof tuple> // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}
```
这个题抄答案了
我们用的
```
type TupleToObject<T extends readonly any[]> = {
]:P
}
```
其中T是通过索引类型签名来获取内容的联合集合
然后进行遍历
具体可以参考
https://bbs.tampermonkey.net.cn/thread-2766-1-1.html
页: [1]
查看完整版本: typescript类型体操记录贴(四)Tuple to Object