Sub topic 10
Recursive types: splitting and parsing strings
Earlier chapters used infer inside a template literal type to pull one piece out of a string type. This chapter combines that with recursion. A recursive type can walk a string of any length and produce a tuple, another string, or an object type.
This chapter assumes you are comfortable with conditional types, infer, generics with constraints, and the template literal syntax from the previous chapters. A few examples use infer X extends T, which needs TypeScript 4.7 or later. The tail-recursion behavior described later needs 4.5 or later.
Why one `infer` is not enough
A pattern with two infer positions and one delimiter splits a string exactly once:
type SplitOnce<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}` ? [Head, Tail] : [S];
type A = SplitOnce<"a-b-c", "-">; // ["a", "b-c"]The result is ["a", "b-c"], not ["a", "b", "c"]. When TypeScript matches a template pattern, each infer placeholder that is followed by literal text captures the shortest string that lets the rest of the pattern match. Head therefore stops at the first -, and Tail takes everything after it.
The fix is to apply the same type to Tail. A type alias can refer to itself inside a conditional type, so we can write a loop with no loop syntax.
Building Split
This is the recursive version:
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}`
? [Head, ...Split<Tail, D>]
: [S];
type Parts = Split<"a-b-c", "-">; // ["a", "b", "c"]The type has two branches:
- Recursive case. The string contains the delimiter. Put
Headin the result tuple and spread the result of splittingTailafter it. - Base case. The string does not contain the delimiter. Return it as the only element. Without a base case, the recursion would never stop.
The following diagram shows the evaluation of Split<"a-b-c", "-">.
TypeScript evaluates the type from the top down, but the tuple is assembled on the way back up. The [Head, ...Split<Tail, D>] expression cannot finish until the inner Split has finished. This detail matters in the section on limits below.
Edge cases
Check these inputs before you rely on a string parser:
| Input | Result | Why |
|---|---|---|
| `Split<"abc", "-">` | `["abc"]` | No delimiter, so the base case runs at once. |
| `Split<"", "-">` | `[""]` | The empty string has no delimiter. This matches `"".split("-")` at runtime. |
| `Split<"a,b,", ",">` | `["a", "b", ""]` | A trailing delimiter leaves an empty `Tail`. This matches runtime behavior. |
| `Split<"a--b", "-">` | `["a", "", "b"]` | Adjacent delimiters give an empty `Head`. |
| `Split<string, ",">` | `[string]` | A non-literal `string` cannot match the pattern, so you get a single `string` element. |
The last row of the table is a useful property. When the input is not a literal type, such as a value read from user input, the type degrades to a safe answer instead of an error.
Using Split on a real value
Types are erased at runtime, so a runtime function must do the actual splitting. The type then describes what that function returns:
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}`
? [Head, ...Split<Tail, D>]
: [S];
function split<S extends string, D extends string>(
text: S,
delimiter: D
): Split<S, D> {
return text.split(delimiter) as unknown as Split<S, D>;
}
const parts = split("2026-11-25", "-");
// parts: ["2026", "11", "25"]
const year = parts[0]; // type "2026"
// const bad = parts[3]; // Error: Tuple type has no element at index '3'The as unknown as cast is needed because TypeScript cannot prove that string[] is assignable to an unresolved conditional type. The cast is a promise you make to the compiler, so it is only as good as the match between the type and the runtime behavior. The edge-case table above is the check that they agree.
Trimming whitespace
Many parsers need to ignore spaces around a token. Trimming is a simple recursion that removes one character per step:
type TrimLeft<S extends string> =
S extends ` ${infer Rest}` ? TrimLeft<Rest> : S;
type TrimRight<S extends string> =
S extends `${infer Rest} ` ? TrimRight<Rest> : S;
type Trim<S extends string> = TrimLeft<TrimRight<S>>;
type T = Trim<" hello ">; // "hello"TrimRight works because the pattern ${infer Rest} ends with a literal space. TypeScript matches the final space, and Rest captures everything before it. Each recursive call removes one space, and the recursion stops when no space remains at that end.
Joining a tuple back into a string
Recursion also runs in the other direction. This type turns a tuple of strings into one string:
type Join<T extends readonly string[], D extends string> =
T extends readonly []
? ""
: T extends readonly [infer Only extends string]
? Only
: T extends readonly [infer First extends string, ...infer Rest extends string[]]
? `${First}${D}${Join<Rest, D>}`
: string;
type J = Join<["a", "b", "c"], "-">; // "a-b-c"The second branch handles a one-element tuple so that no trailing delimiter is added. The final string branch covers tuples of unknown length, such as string[]. There the exact result cannot be known, so the type falls back to the widest correct answer.
Parsing: a query string
Parsing combines splitting with building an object type. Here we turn "page=2&sort=asc" into { page: "2"; sort: "asc" }:
type ParsePair<S extends string> =
S extends `${infer Key}=${infer Value}`
? { [P in Key]: Value }
: { [P in S]: true };
type ParseQuery<S extends string> =
S extends ""
? {}
: S extends `${infer Pair}&${infer Rest}`
? ParsePair<Pair> & ParseQuery<Rest>
: ParsePair<S>;
type Simplify<T> = { [K in keyof T]: T[K] } & {};
type Query = Simplify<ParseQuery<"page=2&sort=asc&debug">>;
// { page: "2"; sort: "asc"; debug: true }There are three layers:
ParsePairhandles onekey=valuesegment. A segment with no=becomes a flag set totrue.ParseQuerysplits on&and recurses. It combines the pieces with&, the intersection operator.Simplifyflattens the intersection into a single object type. The mapped type walks every key of the intersection and rebuilds it as one object. The result is the same type, but it is easier to read in editor hovers and error messages.
Keys and values are inferred as string literal types, so Query["page"] is "2", not string. That precision is the reason to parse at the type level. A function that accepts a query string literal can return a correctly typed object without any manual declaration.
Limits of recursion
Recursive string types are evaluated by the compiler every time they are used, and the compiler has guards against runaway work.
Depth
A recursive type that is not in tail position, like Split above, builds up pending work: each level waits on the level below it. The compiler limits how deep this nesting can go. The limit is on the order of a hundred levels. Past it you get the error Type instantiation is excessively deep and possibly infinite. A string with a few hundred delimiters would hit this limit.
TypeScript 4.5 added tail-recursion elimination for conditional types. If the recursive call is the entire result of a branch, the compiler can evaluate it as a loop. Its limit is about 1000 iterations. To use it, carry the partial result in an extra parameter, called an accumulator:
type SplitFast<
S extends string,
D extends string,
Acc extends string[] = []
> = S extends `${infer Head}${D}${infer Tail}`
? SplitFast<Tail, D, [...Acc, Head]>
: [...Acc, S];
type Fast = SplitFast<"a-b-c", "-">; // ["a", "b", "c"]The recursive call to SplitFast is now the whole result of its branch. The tuple grows in Acc instead of after the call returns. The two versions give the same answers, so the accumulator form is a safe default when inputs might be long.
Size and speed
Each evaluated type costs compile time. Three habits help:
- Keep inputs short. Parsing a 50-character route is fine. Parsing a whole document at the type level is not.
- Avoid unions of many members as input to a recursive type. A conditional type distributes over a union, so a union of 200 strings starts 200 separate recursions.
- Use these types for configuration, route tables, and API names. Do not use them for data that arrives at runtime.
Precision
A recursive type can only parse what the compiler can see as a literal. If a caller passes a plain string, the result falls to the base case, such as [string]. If a parser must accept real user input, give the function a runtime check and treat the type as a description of the literal cases only.
Summary
- A single
inferpattern matches once, so use recursion to process a string of unknown length. - Every recursive type needs a base case and a recursive case. The recursive case must consume part of the input.
- Test edge cases: empty strings, adjacent and trailing delimiters, and non-literal
stringinput. - Use an accumulator parameter to put the recursive call in tail position when inputs may be long.
- Keep parsers small. Type-level parsing is a precision tool, not a general-purpose parser.
Exercise
Write a type Words<S> that splits a string on single spaces and trims nothing else, so Words<"hello big world"> is ["hello", "big", "world"]. Then write CountWords<S> that returns the number of words as a numeric literal type. Hint: T["length"] gives the length of a tuple type.
Show answer
type Words<S extends string> =
S extends ${infer Head} ${infer Tail}
? [Head, ...Words<Tail>]
: [S];
type CountWords<S extends string> = Words<S>["length"];
type N = CountWords<"hello big world">; // 3
Words is Split with the delimiter fixed to a space. A tuple's length property is a numeric literal type, so CountWords needs no extra recursion.
Exercise
This type is meant to reverse a string, but it exceeds the depth limit on long inputs. Rewrite it so the recursive call is in tail position.
type Reverse<S extends string> =
S extends ${infer First}${infer Rest}
? ${Reverse<Rest>}${First}
: "";
Show answer
type Reverse<S extends string, Acc extends string = ""> =
S extends ${infer First}${infer Rest}
? Reverse<Rest, ${First}${Acc}>
: Acc;
type R = Reverse<"abc">; // "cba"
In the original, the recursive call sits inside a template literal, so each level must wait for the one below. In the rewrite, the recursive call is the entire branch result. The reversed text is built in the accumulator Acc by putting each new character in front of what was built so far.