Sub topic 10
Recursive Types: Splitting and Parsing Strings
This chapter assumes that you know type aliases, string literal unions, generics, conditional types, infer, and mapped types. It also assumes that you have used template literal types such as ` ${"user"}-${number} `.
A recursive type refers to itself while computing a result. In a string parser, each recursive step consumes part of the string. The recursion must eventually reach a simpler case that does not call the type again.
The shape of a recursive string type
Suppose you want to split "a-b-c" into ["a", "b", "c"]. The type needs two cases:
- If the string contains the delimiter, capture the part before it and recursively process the rest.
- If the string contains no delimiter, return the remaining string as the final part.
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"]
const parts: Parts = ["a", "b", "c"];The conditional type checks whether S matches a template pattern. infer Head creates a type variable for the text before the delimiter. infer Tail captures the text after the delimiter.
The spread syntax in [Head, ...Split<Tail, D>] combines the current part with the tuple produced by the recursive call. The final branch, [S], is the base case. It stops recursion when no delimiter remains.
Following the recursive steps
For Split<"a-b-c", "-">, TypeScript evaluates the type conceptually like this:
| Input | Result of one step |
|---|---|
| `"a-b-c"` | `["a", ...Split<"b-c", "-">]` |
| `"b-c"` | `["b", ...Split<"c", "-">]` |
| `"c"` | `["c"]` |
Combining those results produces ["a", "b", "c"].
A recursive type should make progress at every step. Here, Tail is shorter than the original string whenever a delimiter is found. Without progress, the compiler could recurse forever.
Parsing structured strings
Splitting is useful, but a parser can return a more meaningful structure. For example, an event description might use the format "click:button".
type ParseEvent<S extends string> =
S extends `${infer Event}:${infer Target}`
? {
event: Event;
target: Target;
}
: never;
type ButtonClick = ParseEvent<"click:button">;
// { event: "click"; target: "button" }
const event: ButtonClick = {
event: "click",
target: "button",
};This parser has no recursion because the format contains one separator. To parse multiple segments, add recursion.
type RouteSegments<S extends string> =
S extends `/${infer Segment}/${infer Rest}`
? [Segment, ...RouteSegments<`/${Rest}`>]
: S extends `/${infer Last}`
? [Last]
: [];
type Segments = RouteSegments<"/users/42/posts">;
// ["users", "42", "posts"]The first branch captures one segment and recursively processes the remaining route. The second branch handles the final segment. The last branch handles an empty or already-consumed string.
Common errors
Forgetting the base case
A type that always refers to itself has no stopping condition. TypeScript will eventually report excessive recursion or fail to compute the result.
Recursing without consuming input
Check that each recursive call receives a smaller or simpler string. A call such as Parse<S> inside Parse<S> cannot make progress.
Assuming runtime validation
These types inspect string types during compilation. They do not validate arbitrary runtime strings.
declare const input: string;
type InputParts = Split<typeof input, "-">;
// [string], because the compiler does not know the contents of inputWhen the input type is the broad string type, TypeScript cannot discover its separators. Runtime code is still required to split or validate the actual value.
Creating too many combinations
Recursive parsing often works together with unions. A union at each recursive step can multiply the number of possible results. Keep parsers small and specific when compiler performance matters.
A practical design checklist
- Define the exact string format before writing the type.
- Identify the base case first.
- Capture the current segment with
infer. - Ensure the recursive call receives the unprocessed remainder.
- Test empty strings, missing delimiters, and repeated delimiters.
- Use runtime parsing when the input is only known as
string.
Exercise
What is the result of Split<"one/two", "/">, and which branch stops the recursion?
Show answer
The result is ["one", "two"]. The base branch [S] stops recursion when the remaining input is "two".