I have been working on implementing a versatile split type in TypeScript that can effectively split a literal string using multiple delimiters.
type Spl<T extends string, D extends string> = T extends `${infer A}${D}${infer B}` ?
A extends '' ? [] :
[A, ...Spl<B, D>] : (T extends '' ? [] : [T]);
type SplMany<T extends string, D extends string[]> = D extends [infer H extends string, ...infer Tail extends string[]]
?
T extends '' ? [] : SplManyInputsManyDelimieter<[...Spl<T, H>], Tail>
: [T];
type SplManyInputs<T extends string[], D extends string> = T extends [infer H extends string, ...infer Tail extends string[]]
? [...Spl<H, D>, ...SplManyInputs<Tail, D>] : [];
type SplManyInputsManyDelimieter<T extends string[], D extends string[]> =
D extends [infer H extends string, ...infer Tail extends string[]] ?
SplManyInputsManyDelimieter<[...SplManyInputs<T, H>], Tail>
: T;
type t1 = Spl<'1 2 3 4 5 6 7 8 9 10 11 %test% 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 1 2 3 4 5 6 7 8 9 10 11 %test% 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 1 2 3 4 5 6 7 8 9 10 11 %t...
Upon testing the code, it performs well. However, I encountered an error message as the input strings grew longer:
Type instantiation is excessively deep and possibly infinite. ts(2589)
. It appears that the recursion limit was reached earlier than expected, posing challenges for efficiency.
Are there any strategies I could employ to optimize the code and support longer inputs? Additionally, I attempted to locate the source of the error message within the TypeScript compiler but without success. Does anyone know where this specific error is generated?