Tuple to Union
介绍
实现一个TupleToUnion<T>
泛型, 涵盖元组的值转换为联合类型
For example
ts
type Arr = ['1', '2', '3']const a: TupleToUnion<Arr> // expected to be '1' | '2' | '3'
View on GitHubts
type Arr = ['1', '2', '3']const a: TupleToUnion<Arr> // expected to be '1' | '2' | '3'
起点
ts
/* _____________ Your Code Here _____________ */typeTupleToUnion <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]
take the challengets
/* _____________ Your Code Here _____________ */typeTupleToUnion <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
// 方案1typeTupleToUnion <T extends any[]> =T [number]
ts
// 方案1typeTupleToUnion <T extends any[]> =T [number]