type-challenges-solutions icon indicating copy to clipboard operation
type-challenges-solutions copied to clipboard

type-challenges-solutions/en/medium-string-to-union

Open utterances-bot opened this issue 4 years ago • 1 comments

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

utterances-bot avatar May 07 '21 21:05 utterances-bot

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]

mei33 avatar May 07 '21 21:05 mei33