Skip to content

Instantly share code, notes, and snippets.

@armanozak
Created May 10, 2023 07:12
Show Gist options
  • Save armanozak/849e43d9f2c3ca01812ae93b583230e8 to your computer and use it in GitHub Desktop.
Save armanozak/849e43d9f2c3ca01812ae93b583230e8 to your computer and use it in GitHub Desktop.
Split & Concat Types w/ Delimiter
/*
* Note: This is just for fun.
*/
type Split<T extends string, Delimiter extends string = ""> =
"" extends T
? []
: T extends `${infer Head}${Delimiter}${infer Tail}`
? [Head, ...Split<Tail, Delimiter>]
: [T];
type Concat<T extends string[], Delimiter extends string = ""> =
T extends [infer Head extends string, ...infer Tail extends string[]]
? `${Head}${Delimiter}${Concat<Tail>}`
: "";
type S0 = Split<"">; // []
type C0 = Concat<S0>; // ""
type S1 = Split<"", "X">; // []
type C1 = Concat<S1, "X">; // ""
type S2 = Split<"X">; // ["X"]
type C2 = Concat<S2>; // "X"
type S3 = Split<"X", "X">; // [""]
type C3 = Concat<S3, "X">; // "X"
type S4 = Split<"Hello world", " ">; // ["Hello", "world"]
type C4 = Concat<S4, " ">; // "Hello world"
type S5 = Split<"CR#7">; // ["C", "R", "#", "7"]
type C5 = Concat<S5>; // "CR#7"
type S6 = Split<"CR#7", "#">; // ["CR", "7"]
type C6 = Concat<S6, "#">; // "CR#7"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment