跳到主要内容

Tuple to Union

介绍

实现一个TupleToUnion<T>泛型, 涵盖元组的值转换为联合类型

For example

ts
type Arr = ['1', '2', '3']
const a: TupleToUnion<Arr> // expected to be '1' | '2' | '3'
ts
type Arr = ['1', '2', '3']
const a: TupleToUnion<Arr> // expected to be '1' | '2' | '3'
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type TupleToUnion<T> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<TupleToUnion<[123, '456', true]>, 123 | '456' | true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TupleToUnion<[123]>, 123>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
ts
/* _____________ Your Code Here _____________ */
 
type TupleToUnion<T> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<TupleToUnion<[123, '456', true]>, 123 | '456' | true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TupleToUnion<[123]>, 123>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
// 方案1
type TupleToUnion<T extends any[]> = T[number]
 
ts
// 方案1
type TupleToUnion<T extends any[]> = T[number]
 
view more solutions