Yuzhe's Blog

yuzhes

元组转合集

元组转合集

题目链接

题目

实现泛型TupleToUnion<T>,它返回元组所有值的合集。

例如

type Arr = ['1', '2', '3']

type Test = TupleToUnion<Arr> // expected to be '1' | '2' | '3'

解答

type TupleToUnion<T extends readonly unknown[]> = T[number]

T[number]可以用来获取元组的所有值的联合类型,因为Array类型有number索引签名

interface ArrayMaybe<Element> {
    [index: number]: Element;
}

同样的,对于这样定义的Dictionary类型,T[string]可以用来获取对象的所有值的联合类型。

interface Dictionary<Value> {
    [key: string]: Value;
}

:::tip 你可以使用索引类型的键的类型来获取此索引的值的联合类型。 :::

类似的,T[keyof T]可以用来获取对象的所有值的联合类型。