Last active
October 13, 2023 21:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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