-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Description
10 - Tuple To Union
Tuple To Union reinforces some essential skills for going between tuples and unions, something we're going to find ourselves needing to do a lot in later challenges. This is a fun one.
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type A1 = TupleToUnion<[123, '456', true]>
type B1 = 123 | '456' | true;
type C1 = Expect<Equal<A1, B1>>;
type A2 = TupleToUnion<[123]>
type B2 = 123;
type C2 = Expect<Equal<A2, B2>>;
// ============= Your Code Here =============
type TupleToUnion<T extends unknown[]> = T[number];
// ============== Alternatives ==============
type TupleToUnion<T> =
T extends unknown[]
? T[number]
: never;
type TupleToUnion<T> = T[number & keyof T];
// using builtin `Extract`
type Extract<T, U> = T extends U ? T : never;
type TupleToUnion<T> = T[Extract<keyof T, number>];
type TupleToUnion<T> =
T extends (infer R)[]
? R
: never;
type TupleToUnion<T> =
T extends [infer Head, ...infer Tail]
? Head | TupleToUnion<Tail>
: never;
type TupleToUnion<T> = T[any];
type TupleToUnion<T extends any[]> = keyof {
[K in T[number]]: K;
};➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
No labels