type-challenges-solutions/en/medium-string-to-union
String to Union
This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.
https://ghaiklor.github.io/type-challenges-solutions/en/medium-string-to-union.html
Challenge can be solved via our work from `Length of String by using an accumulator. We can split string to first and rest of letters, saving first letter to the accumulator on each step. String with a length of one letter will be splitted to the letter itself and an empty string. Calling our type with the empty string will evaluate second expression of a ternary operator. All we have to do - create a union of all of the accumulator's elements:
type StringToUnion<T extends string, A extends string[] = []> = T extends `${infer H}${infer T}` ? StringToUnion<T, [...A, H]> : A[number]