Skip to main content

元组转换为对象

题目

传入一个元组类型,将这个元组类型转换为对象类型,这个对象类型的键/值都是从元组中遍历出来。

例如:

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'}

题目来源:https://tsch.js.org/11/zh-CN

解答

type TupleToObject<T extends readonly any[]> = {
[P in T[number]]: P
}

思路

T[number]是什么?

先看看TypeScript的一个例子:

type Flatten<T> = T extends any[] ? T[number] : T;

// Extracts out the element type.
type Str = Flatten<string[]>;

`type Str = string`

// Leaves the type alone.
type Num = Flatten<number>;

`type Num = number`

泛型T是数组,数组以number为索引,所以T[number]对应数组中的每个值。

[P in T[number]]

使用in遍历T[number],也即遍历泛型数组T中的每个值。