Skip to content

Instantly share code, notes, and snippets.

@LeandrodeLimaC
Last active October 13, 2023 21:56
Show Gist options
  • Save LeandrodeLimaC/3ed0b6fa19decda52d532fc083350825 to your computer and use it in GitHub Desktop.
Save LeandrodeLimaC/3ed0b6fa19decda52d532fc083350825 to your computer and use it in GitHub Desktop.
Simple implementation of a recursive Utility Type to extract substrings using a delimiter
/**
* Splits a string based type into an tuple using a delimiter.
*
* @template S - The input string to be split.
* @template D - The delimiter string used for splitting.
* @template T - The resulting array of substrings.
*
* @returns A tuple of strings representing the segments of the original string after being split by the delimiter.
*
* @example
* // Split a comma-separated string
* type Result = Split<"apple,banana,cherry", ",", []>;
* // Result: ["apple", "banana", "cherry"]
*/
type Split<
S extends string,
D extends string,
T extends string[] = []
> =
S extends `${infer BD}${D}${infer AD}`
? Split<AD, D, [...T, BD]>
: [...T, S];
// ----
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment