Sub topic 10
Parsing String Literal Types with `infer`
This chapter assumes you know TypeScript generics, conditional types, union types, and basic template literal types. The goal is to use infer to split a string literal type into smaller parts, then recurse over those parts.
Matching a template literal pattern
A template literal type can describe the shape of a string. In a conditional type, infer captures the text matched by a pattern.
type ExtractRouteId<S extends string> =
S extends `/users/${infer Id}` ? Id : never;
type UserId = ExtractRouteId<"/users/42">; // "42"
type Invalid = ExtractRouteId<"/posts/42">; // neverWhen TypeScript checks "/users/42" against ` /users/${infer Id} , the fixed text /users/ must match first. The remaining text is captured as Id`.
The result is a string literal type, not the broad string type. This preserves information that other type operations can use.
type EventName<S extends string> =
S extends `on${infer Name}` ? Name : never;
type Click = EventName<"onClick">; // "Click"The inferred section can appear more than once, although repeated patterns can be harder to predict. Prefer patterns with clear delimiters.
Recursively splitting a string
To split a string at every delimiter, match one piece, then call the type again with the remaining text.
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}`
? [Head, ...Split<Tail, D>]
: [S];
type Parts = Split<"api.users.list", ".">;
// ["api", "users", "list"]
type Words = Split<"red-green-blue", "-">;
// ["red", "green", "blue"]The conditional type has two branches:
- If
ScontainsD,Headreceives the text before the first delimiter andTailreceives the rest. - If
Sdoes not containD, the type returns a one-element tuple containingS.
That second branch is the base case. It stops recursion when no delimiter remains.
Controlling the match
The delimiter type can be a literal such as ".", or a union of possible delimiters.
type SplitOnSlashOrDot<S extends string> =
S extends `${infer Head}${"." | "/"}${infer Tail}`
? [Head, ...SplitOnSlashOrDot<Tail>]
: [S];
type Result = SplitOnSlashOrDot<"api/users.list">;
// ["api", "users", "list"]This is useful for small parsers, but a broad delimiter or broad input can produce less precise results. If S is just string, TypeScript cannot identify a specific head or tail.
type UnknownParts = Split<string, ".">;
// Usually a broad result, because string has no known delimiter position.You can also constrain an inferred part. This pattern keeps only strings whose first section matches a required shape.
type FirstSegment<S extends string> =
S extends `${infer First extends "api" | "web"}${"."}${string}`
? First
: never;
type Api = FirstSegment<"api.users">; // "api"
type Other = FirstSegment<"admin.users">; // neverThe constraint infer First extends "api" | "web" makes the match fail when the captured text is outside that union.
Testing the result
Type-level code has no runtime output, so test it with compile-time assertions.
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 _SplitTest = Expect<
Equal<Split<"a.b.c", ".">, ["a", "b", "c"]>
>;If the implementation returns a different tuple, the Expect line becomes a compile-time error.
Exercise
What is the result of Split<"one/two", "/">?
Show answer
It is ["one", "two"]. The first recursive match captures "one" and "two", then the second branch returns ["two"].