-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Labels
531answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English
Description
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
🔢 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
Labels
531answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English