yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

00010-medium-tuple-to-union #10

Open yunliuyan opened 11 months ago

yunliuyan commented 11 months ago

元组转合集 中等 #infer #tuple #union

by Anthony Fu @antfu

接受挑战    English 日本語 한국어

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

例如

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

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

测试案例:

import type { Equal, Expect } from '@type-challenges/utils'

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

返回首页 分享你的解答 查看解答

相关挑战

11・元组转换为对象 472・Tuple to Enum Object 730・Union to Tuple 3188・Tuple to Nested Object
yunliuyan commented 11 months ago

思路

T[number] 索引访问语法,用于访问元组的联合类型

代码

type MyTupleToUnion<T extends readonly any[]> = T[number]
Janice-Fan commented 11 months ago
type TupleToUnion<T extends any[]> = T[number]

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

type Test = TupleToUnion<Arr> // expected to be '1' | '2' | '3'
Naparte commented 11 months ago

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

type TupleToUnion<T extends readonly any[]> = keyof {
    [key in T[number]]: key
}

// type MyTupleToUnion<T extends readonly any[]> = T[number]

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

type Test = TupleToUnion<Arr> // expected to be '1' | '2' | '3'
wudu8 commented 11 months ago
type MyTupleToUnion<T extends readonly any[]> = T[number]

type TupleToUnionArr = ['a', '2', 3, true]

type MyTupleToUnionTest = MyTupleToUnion<TupleToUnionArr> // expected to be true | "a" | "2" | 3
type MyTupleToUnionTest2 = MyTupleToUnion<['a', '2', 3, true]> // expected to be true | "a" | "2" | 3