Skip to content

Latest commit

 

History

History
35 lines (31 loc) · 945 Bytes

File metadata and controls

35 lines (31 loc) · 945 Bytes

Recursive to reuse

When encountering an uncertain number of problems, you have to reflexively think of recursion. For example, the length of the array is uncertain, the length of the string is uncertain, and the number of index type layers is uncertain.

type ReverseStr<
    Str extends string, 
    Result extends string = ''
> = Str extends `${infer First}${infer Rest}` 
    ? ReverseStr<Rest, `${First}${Result}`> 
    : Result;
type StringToUnion<Str extends string> = 
    Str extends `${infer First}${infer Rest}`
        ? First | StringToUnion<Rest>
        : never;
type ReplaceAll<
    Str extends string, 
    From extends string, 
    To extends string
> = Str extends `${infer Left}${From}${infer Right}`
        ? `${Left}${To}${ReplaceAll<Right, From, To>}`
        : Str;