这是indexloc提供的服务,不要输入任何密码
Skip to content

10 - Tuple To Union (🎥 Video Explanation and Solution) #21547

@dimitropoulos

Description

@dimitropoulos

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

Release Date: 2023-01-19 19:00 UTC

Tuple To Union

🔢 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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions