Sub topic 7
Extracting Parts of a String with `infer`
Prerequisites and the working model
This chapter assumes that you know basic TypeScript types, string literal unions, generics, conditional types, and mapped types.
A template literal type can describe the shape of a string. A conditional type can test whether another type matches that shape. The infer keyword names a part captured during that match.
The general pattern is:
type ExtractPart<T extends string> =
T extends `prefix-${infer Part}`
? Part
: never;If T is "prefix-blue", the pattern matches and Part becomes "blue". If T does not match, the result is never, which means that no value remains in the type.
Matching one part
The following type extracts everything after user-:
type UserId<T extends string> =
T extends `user-${infer Id}` ? Id : never;
type FirstId = UserId<"user-42">; // "42"
type SecondId = UserId<"user-alex">; // "alex"
type NotAnId = UserId<"team-42">; // neverinfer Id does not convert the result into a JavaScript value. It creates a type variable named Id for the true branch of the conditional type.
You can use the extracted type in another type expression:
type EventPayload<T extends string> =
T extends `event:${infer Name}`
? { name: Name }
: never;
type Payload = EventPayload<"event:created">;
// { name: "created" }The literal "created" remains specific. If the input is a union, conditional types usually distribute over that union:
type Names = EventPayload<"event:created" | "event:deleted">;
// { name: "created" } | { name: "deleted" }Capturing multiple pieces
A template pattern can contain more than one infer variable. Consider a path with a resource and an identifier:
type ResourceAndId<T extends string> =
T extends `/${infer Resource}/${infer Id}`
? { resource: Resource; id: Id }
: never;
type Result = ResourceAndId<"/users/42">;
// { resource: "users"; id: "42" }The slash characters are fixed parts of the pattern. The two infer variables capture the text between those fixed parts.
When a pattern has repeated or ambiguous portions, inference can be less obvious. TypeScript must choose a match that satisfies the entire template. Use clear delimiters such as /, :, or - when designing formats for type-level parsing.
Route parameter names
A useful application is extracting parameter names from a route. A route such as /users/:id/posts/:postId contains two parameter names.
type ExtractRouteParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | ExtractRouteParams<`/${Rest}`>
: T extends `${string}:${infer Param}`
? Param
: never;
type RouteParams =
ExtractRouteParams<"/users/:id/posts/:postId">;
// "id" | "postId"The first conditional branch finds a colon, captures the text up to the next slash, and recursively processes the remainder. The second branch handles the final parameter, which has no slash after it.
This type extracts names only. It does not create an object or validate a route at runtime.
Visualizing recursive matching
Common errors
A common mistake is forgetting the fallback branch:
type Broken<T extends string> =
T extends `user-${infer Id}` ? Id : string;This returns string for every nonmatching input, which loses useful information. Use never when a nonmatch should be rejected or removed from a union.
Another mistake is using an unconstrained generic:
type Invalid<T> = T extends `user-${infer Id}` ? Id : never;Depending on the operation, TypeScript may require T to be constrained to string. Add T extends string when matching a string template.
Finally, remember that extracted text is still a string literal. "42" is not the number 42. A type such as UserId<"user-42"> produces "42", not 42.
type Extracted = UserId<"user-42">;
const textId: Extracted = "42";
// const numericId: Extracted = 42; // ErrorExercise
What is the result of ExtractRouteParams<"/teams/:teamId">?
Show answer
"teamId". The final conditional branch captures the text after the colon because no later slash remains.