huihuilang53 / ts-challenges

ts类型体操刷题总结

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

元组转联合类型

huihuilang53 opened this issue · comments

commented

/*
10 - 元组转合集

by Anthony Fu (@antfu) #中等 #infer #tuple #union

题目

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

例如

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

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

在 Github 上查看:https://tsch.js.org/10/zh-CN
*/

/* _____________ 你的代码 _____________ */

type TupleToUnion<T> = T extends [infer first ,...infer rest] ? first | TupleToUnion<rest> :never
type a = TupleToUnion<[123, '456', true]>

/* _____________ 测试用例 _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

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

/* _____________ 下一步 _____________ /
/

分享你的解答:https://tsch.js.org/10/answer/zh-CN
查看解答:https://tsch.js.org/10/solutions
更多题目:https://tsch.js.org/zh-CN
*/

commented

更简单的办法 : type TupleToUnion<T extends any[]> = T[number]