[TypeScript] Type Challenges #10 - Tuple to Union

83 阅读1分钟

题目描述

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

例如

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

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

题解

// ============= Test Cases =============
import type { EqualExpect } from './test-utils'

type cases = [
  Expect<Equal<TupleToUnion<[123'456'true]>, 123 | '456' | true>>,
  Expect<Equal<TupleToUnion<[123]>, 123>>,
]


// ============= Your Code Here =============
type TupleToUnion<T extends unknown[]> = T[number]

使用T extends unknown[]对传入的类型参数T进行约束,确保T是一个数组或元组类型

在 TypeScript 中,T[number]是一种索引访问类型查询的语法,它用于获取数组或对象类型中索引签名 number 对应的类型

对于数组或元组,T[number]返回数组或元组中所有元素类型的联合类型