Sub topic 10
Parsing string literal types with infer
This chapter assumes you can read conditional types, use infer to capture a type, and write simple recursive conditional types with a base case. It also assumes you know basic template literal types such as ` ${A}-${B} `. Here you will combine these to take a string apart at the type level.
What a string literal type is
A string literal type is a type with exactly one value, such as 'a.b.c'. When a type parameter is instantiated with such a type, a template literal pattern can match it and capture pieces with infer.
type Greeting<S extends string> = S extends `Hello, ${infer Name}!` ? Name : never;
type G1 = Greeting<'Hello, Ada!'>; // 'Ada'
type G2 = Greeting<'Goodbye, Ada!'>; // neverThe pattern has a fixed prefix, Hello, , a capture, and a fixed suffix, !. TypeScript checks the prefix and suffix, and whatever is between them becomes Name. If the prefix or suffix does not match, the conditional type takes the false branch.
How the matcher assigns text to captures
The matching rules decide what every capture contains. They are simple, but they cause most of the surprises.
| Pattern shape | What each `infer` captures |
|---|---|
| `` `${infer A}.${infer B}` `` | `A` is the text before the first `.`. `B` is everything after it, including later dots. |
| `` `${infer A}${infer B}` `` | `A` is exactly one character. `B` is the rest. |
| `` `${infer A}.` `` | `A` is everything before a trailing `.`. |
| `` `${infer A}${D}${infer B}` `` with `D` set to `''` | The pattern collapses to the two-capture form above, so `A` is one character. |
The last capture in a pattern takes the remainder of the string. Every capture followed by a literal delimiter takes the shortest text that lets the delimiter match. This "first delimiter wins" behavior is what makes recursion over strings work: each step peels off one piece and passes the rest to the next step.
The diagram traces Split<'a.b.c', '.'>.
Splitting on a delimiter
This is the splitter from the plan, with the reasoning for each branch spelled out.
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']
type Single = Split<'abc', '.'>; // ['abc']
type Trailing = Split<'a.', '.'>; // ['a', '']The true branch handles "a delimiter exists". The false branch is the base case: no delimiter remains, so the whole remaining string is the last element. Because the base case returns [S] and not [], an input with no delimiter still produces a one-element tuple.
Trailing shows an edge case. After a is removed, the tail is the empty string. The empty string contains no ., so the base case returns ['']. This matches 'a.'.split('.') at runtime, which also returns ['a', ''].
Trimming whitespace
Fixed text can sit at either end of a pattern, so one alias can strip the start and another can strip the end.
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'Each step removes one space and calls itself again. The false branch returns S unchanged, which ends the recursion once no space is left at that end.
Replacing text
A replace helper keeps the prefix and the suffix and rebuilds the string around the new text. The From extends '' guard prevents an infinite loop, because an empty search string matches at every position.
type ReplaceAll<S extends string, From extends string, To extends string> =
From extends ''
? S
: S extends `${infer Head}${From}${infer Tail}`
? `${Head}${To}${ReplaceAll<Tail, From, To>}`
: S;
type Dashed = ReplaceAll<'a.b.c', '.', '-'>; // 'a-b-c'Note what the recursion does here. It runs on Tail, which is shorter than S at every step, so the recursion always makes progress toward the base case.
Changing case with intrinsic helpers
Template literal types come with four built-in string types: Uppercase, Lowercase, Capitalize and Uncapitalize. Combined with a split, they convert naming styles.
type SnakeToCamel<S extends string> =
S extends `${infer Head}_${infer Tail}`
? `${Head}${Capitalize<SnakeToCamel<Tail>>}`
: S;
type Camel = SnakeToCamel<'user_first_name'>; // 'userFirstName'
type CamelKeys<T> = {
[K in keyof T as K extends string ? SnakeToCamel<K> : K]: T[K];
};
type Row = { user_id: number; first_name: string };
type Model = CamelKeys<Row>; // { userId: number; firstName: string }CamelKeys uses a mapped type with an as clause (key remapping). The string parser runs once for each key, and the property types pass through unchanged. This pairing of a string parser with a mapped type is common in real code, for example when typing database rows or API responses.
Extracting route parameters
A more practical parser pulls :name segments out of a URL pattern and builds an object type from them.
type PathParams<S extends string> =
S extends `${string}:${infer Param}/${infer Rest}`
? Param | PathParams<`/${Rest}`>
: S extends `${string}:${infer Param}`
? Param
: never;
type Params<S extends string> = { [K in PathParams<S>]: string };
type UserPost = Params<'/users/:id/posts/:postId'>;
// { id: string; postId: string }
declare function getRoute<S extends string>(path: S, params: Params<S>): string;
getRoute('/users/:id/posts/:postId', { id: '1', postId: '9' }); // compiles
// getRoute('/users/:id', { name: 'x' }); // error: 'name' does not existThe first pattern uses ${string} as a non-capturing wildcard. It skips everything up to the first :. The branch then captures the parameter name up to the next / and recurses on the rest, re-adding the leading slash so the next step sees a consistent shape. The second pattern handles a parameter that ends the string. The base case is never, which disappears from a union, so a path without parameters gives an empty object type.
Because S is inferred from the string argument, getRoute checks the second argument against the first at compile time. This works only because path is inferred as a literal. If you pass a variable of type string, there is nothing to parse (see the gotchas below).
Parsing numbers
Since TypeScript 4.8, a capture can carry a number constraint. The match succeeds only if the captured text round-trips to a number, and the result is the numeric literal type.
type ParseInt<S extends string> = S extends `${infer N extends number}` ? N : never;
type N1 = ParseInt<'42'>; // 42
type N2 = ParseInt<'4x'>; // neverThis is the infer U extends T form from earlier in the tutorial applied to a string position. It is useful when a string such as '8080' should become a typed port number.
Gotchas and failure modes
- Wide strings do not parse.
Split<string, '.'>evaluates to[string]. The typestringis not a literal, so the pattern cannot match and the base case runs. If you see unexpectedly vague results, check whether the input was widened, for example by aletvariable or a missingas const. - Unions distribute.
Sis a naked type parameter, soSplit<'a.b' | 'c', '.'>is evaluated once per member and gives['a', 'b'] | ['c']. That is usually what you want. Wrap both sides in square brackets if you need to prevent it. - Template literal types have limits. A template that produces more than about 100,000 union members is rejected. Parsing a single string does not hit this, but combining parsers with big unions can.
- Recursion depth is finite. Ordinary recursive conditional types stop at roughly a hundred nested instantiations, with the error "Type instantiation is excessively deep and possibly infinite". A form where the recursive call is the entire result of a branch is treated as tail-recursive and allowed far deeper (about 1,000).
Splitis not tail-recursive, because it wraps the recursive call in a tuple spread. A long input string, such as a 200-segment path, can fail. The final chapters on limits show how to rewrite such types with an accumulator. - Delimiters that appear in captures. The first delimiter always wins, so
Split<'a..b', '.'>yields['a', '', 'b']. If you need quoted or escaped delimiters, a type-level parser quickly becomes hard to maintain. At that point consider validating at runtime instead.
Checking your parsers
Type-level code has no runtime output, so confirm results with a compile-time assertion. This helper is the one introduced in the final chapter, shown here so you can try it now.
type Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}` ? [Head, ...Split<Tail, D>] : [S];
type _T1 = Expect<Equal<Split<'a.b.c', '.'>, ['a', 'b', 'c']>>;
type _T2 = Expect<Equal<Split<'abc', '.'>, ['abc']>>;
type _T3 = Expect<Equal<Split<'a.', '.'>, ['a', '']>>;If you change an expected tuple, the matching line becomes a compile error. Run tsc --noEmit to check the file.
Choosing this approach
Parsing strings in types pays off when a string argument encodes structure that other types depend on: route patterns, event names such as 'user:created', dotted property paths, and SQL or CSS-like mini languages in small cases. It is a poor fit for large grammars. Error messages get long, compile time grows with input length, and the code is hard for teammates to read. Prefer a plain approach when a union of literal strings or an object map can describe the same thing.
Exercise
Write a type Join<T extends string[], D extends string> that is the inverse of Split, so Join<['a', 'b', 'c'], '-'> gives 'a-b-c', Join<['a'], '-'> gives 'a' and Join<[], '-'> gives ''. Which branch is the base case?
Show answer
Use type Join<T extends string[], D extends string> = T extends [infer H extends string, ...infer R extends string[]] ? (R extends [] ? H : ${H}${D}${Join<R, D>}) : ''. The tuple pattern peels off the first element, and the inner check R extends [] stops before adding a trailing delimiter, so the one-element case returns H alone. That inner check is the base case for non-empty tuples. The outer false branch, '', handles the empty tuple. Without the R extends [] check, Join<['a'], '-'> would give 'a-'.
Exercise
What does PathParams<'/health'> evaluate to, and why does Params<'/health'> still compile as a usable type?
Show answer
PathParams<'/health'> is never, because neither pattern finds a :. Mapping over never with [K in never] produces an empty object type {}, so Params<'/health'> is a valid type that requires no parameters.