|
| 1 | +--- |
| 2 | +title: 元组转换为对象 |
| 3 | +--- |
| 4 | + |
| 5 | +# {{ $frontmatter.title }} |
| 6 | + |
| 7 | +## 题目描述 |
| 8 | + |
| 9 | +传入一个元组类型,将这个元组类型转换为对象类型,这个对象类型的键/值都是从元组中遍历出来。 |
| 10 | + |
| 11 | +例如: |
| 12 | + |
| 13 | +```ts |
| 14 | +const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const; |
| 15 | + |
| 16 | +// expected { tesla: 'tesla', 'model 3': 'model 3', |
| 17 | +// 'model X': 'model X', 'model Y': 'model Y' } |
| 18 | +type result = TupleToObject<typeof tuple>; |
| 19 | +``` |
| 20 | + |
| 21 | +## 分析 |
| 22 | + |
| 23 | +此题目标是生成一个新的对象类型,其键值和属性值就是传入的元组的每一项的值,在前面的题目中我们了解了遍历一个对象的方法,加以改动,就可以改为生成一个对象的方法,如下,给定一个联合类型 `'a' | 'b'`,生成一个新的对象: |
| 24 | + |
| 25 | +```ts |
| 26 | +// PropertyKey 是 ts 内置类型:type PropertyKey = string | number | symbol |
| 27 | +type Test<K extends PropertyKey> = { |
| 28 | + [P in K]: P; |
| 29 | +}; |
| 30 | + |
| 31 | +// ['a']: 'a' |
| 32 | +// ['b']: 'b' |
| 33 | +// Case1 = { a: 'a', b: 'b' } |
| 34 | +type Case1 = Test<'a' | 'b'>; |
| 35 | +``` |
| 36 | + |
| 37 | +目前就比较接近了,但是题目给的是元组,所以需要把元组转换成联合类型,可以使用官方提供的 `T[number]` 写法,即可将元组转换为联合类型, |
| 38 | + |
| 39 | +```ts |
| 40 | +type Tuple = [string, number]; |
| 41 | + |
| 42 | +type Case2 = Tuple[number]; // string | number |
| 43 | +``` |
| 44 | + |
| 45 | +```ts |
| 46 | +// 平时工作中经常在不清楚全部属性名称的时候,会 [key: string] 来代替具体的属性名称 |
| 47 | +type MyObject<T> = { |
| 48 | + [key: string]: T; |
| 49 | +}; |
| 50 | + |
| 51 | +// Case1 = T = number | string |
| 52 | +type Case1 = MyObject<number | string>[string]; |
| 53 | +``` |
| 54 | + |
| 55 | +而数组的 `T[number]` 访问与此类似: |
| 56 | + |
| 57 | +```ts |
| 58 | +// 类数组的类型声明 |
| 59 | +type MyArrayLike<T> = { |
| 60 | + [key: number]: T; |
| 61 | +}; |
| 62 | +// MyArrayLike<string> 的属性有 number |
| 63 | +// 所以可以通过索引签名访问的特性访问到 MyArrayLike<string>[number] |
| 64 | +type Case3 = ArrayLike<string>[number]; |
| 65 | +``` |
| 66 | + |
| 67 | +## 题解 |
| 68 | + |
| 69 | +了解了元组转为联合类型的方法后,答案也就呼之欲出了: |
| 70 | + |
| 71 | +```ts |
| 72 | +type TupleToObject<T extends readonly PropertyKey[]> = { |
| 73 | + [P in T[number]]: P; |
| 74 | +}; |
| 75 | +``` |
| 76 | + |
| 77 | +这里也是,需要对输入的元组进行类型限制,其元素必须是 `PropertyKey`(ts 内置类型: `type PropertyKey = string | number | symbol`)。 |
| 78 | + |
| 79 | +## 知识点 |
| 80 | + |
| 81 | +1. `T[number]` 索引签名访问,元组转联合类型 |
0 commit comments