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

531 - String to Union (🎥 Video Explanation and Solution) #22786

@dimitropoulos

Description

@dimitropoulos

531 - String to Union

There are many challenges like this that ask you to take a structure and split it to another. This one asks you to take a string and split each character into the value in a union.

🎥 Video Explanation

Release Date: 2023-02-05 19:00 UTC

String to Union

🔢 Code

// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'

type A1 = StringToUnion<''>;
type B1 = never
type C1 = Expect<Equal<A1, B1>>;

type A2 = StringToUnion<'t'>;
type B2 = 't'
type C2 = Expect<Equal<A2, B2>>;

type A3 = StringToUnion<'hello'>;
type B3 = 'h' | 'e' | 'l' | 'l' | 'o'
type C3 = Expect<Equal<A3, B3>>;

type A4 = StringToUnion<'coronavirus'>;
type B4 = 'c' | 'o' | 'r' | 'o' | 'n' | 'a'
          | 'v' | 'i' | 'r' | 'u' | 's'
type C4 = Expect<Equal<A4, B4>>;

// ============= Your Code Here =============
type StringToUnion<T> =
  T extends `${infer Head}${infer Tail}`
  ? Head | StringToUnion<Tail>
  : never
;

// ============== Alternatives ==============
// extending string is not necessary
// because anything else will fail the condition anyway
type StringToUnion<T extends string> =
  T extends `${infer Head}${infer Tail}`
  ? Head | StringToUnion<Tail>
  : never;

type StringToTuple2<
  T extends string,
  Acc extends string[] = []
> =
  T extends `${infer First}${infer Rest}`
  ? StringToTuple2<Rest, [...Acc, First]>
  : Acc;
type StringToUnion<T extends string> =
  StringToTuple2<T>[number];

export type StringToUnion<
  T extends string,
  Acc extends string[] = []
> =
  T extends `${infer Head}${infer Tail}`
  ? StringToUnion<Tail, [...Acc, Head]>
  : Acc[number];

➕ More Solutions

For more video solutions to other challenges: see the umbrella list! #21338

Metadata

Metadata

Assignees

No one assigned

    Labels

    531answerShare answers/solutions to a questionenin English

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions