Sub topic 7
Extracting parts of a string with infer
This chapter assumes you know conditional types (T extends U ? X : Y), generics with extends constraints, and the template literal syntax from the earlier chapters. You will use infer inside a template literal type to pull pieces out of a string type. Then you will learn the matching rules that decide which piece goes where, and the mistakes that follow from them.
The idea: matching a string against a pattern
A conditional type can test whether a string type fits a template pattern. If you write infer inside a placeholder, TypeScript also captures the part of the string that sits in that position.
type Before<S extends string> = S extends `${infer Head}-${string}` ? Head : never;
type A = Before<"user-42">; // "user"
type B = Before<"plain">; // neverRead ${infer Head}-${string} as "some text, then a hyphen, then any text". If S fits, Head is whatever came before the hyphen. If S does not fit, the conditional takes the false branch.
Two things happen in one step. The pattern is a test, and infer is a capture. A string that fails the test never reaches the capture, so the false branch is where you handle "this is not the shape I expected".
The block above is a placeholder only. The real diagram follows.
The matching rules
The results above follow a small set of rules. Learn them once and the behavior stops being surprising.
- An
inferfollowed by literal text takes the shortest match. TypeScript looks for the first occurrence of that literal and captures everything before it. - The last
infertakes the rest of the string. It has no delimiter after it, so it absorbs everything left. - An
inferdirectly followed by another placeholder takes exactly one character. There is no delimiter to search for, so the first capture is a single character. - Literal text at the end of the pattern must match the end of the string. An
inferjust before it takes everything up to that suffix. - Captures can be empty strings. An empty capture is not a failure.
| Pattern | Input | Result |
|---|---|---|
| `${infer A}-${infer B}` | `"x-y-z"` | A is `"x"`, B is `"y-z"` |
| `${infer A}${infer B}` | `"xyz"` | A is `"x"`, B is `"yz"` |
| `${infer A}-${infer B}` | `"-z"` | A is `""`, B is `"z"` |
| `${infer A}-${infer B}` | `"x-"` | A is `"x"`, B is `""` |
| `${infer A}.ts` | `"app.test.ts"` | A is `"app.test"` |
| `v${infer R}` | `"v1.2.3"` | R is `"1.2.3"` |
| `${infer A}-${infer B}` | `"xyz"` | no match |
Rule 1 is the one that causes the most confusion, so test it directly.
type ParseKV<S extends string> =
S extends `${infer K}=${infer V}` ? { key: K; value: V } : never;
type Theme = ParseKV<"theme=dark">; // { key: "theme"; value: "dark" }
type Eq = ParseKV<"a=b=c">; // { key: "a"; value: "b=c" }
type Missing = ParseKV<"novalue">; // never"a=b=c" splits at the first =. The second = ends up inside V. If you want the split at the last delimiter, a single pattern cannot do it. You need recursion, which a later chapter covers.
Taking the first character
Rule 3 gives you a way to peel one character off a string.
type FirstChar<S extends string> = S extends `${infer F}${infer _Rest}` ? F : never;
type H = FirstChar<"hello">; // "h"
type E = FirstChar<"">; // neverThe empty string has no first character, so the match fails and you get never. This one-character behavior is the building block for the recursive parsers later in the tutorial.
Stripping a known prefix or suffix
When part of the pattern is a type parameter, you can match against a prefix or suffix you supply.
type StripPrefix<S extends string, P extends string> =
S extends `${P}${infer Rest}` ? Rest : S;
type Version = StripPrefix<"v1.2.3", "v">; // "1.2.3"
type Unchanged = StripPrefix<"1.2.3", "v">; // "1.2.3"Here the false branch returns S itself. That is a common design choice for "remove this if present" helpers. Compare it with ParseKV, where a failed match has no sensible result and returns never. Pick the false branch deliberately, because it is part of the type's contract.
Capturing numbers with infer extends
By default every infer inside a template captures a string. Since TypeScript 4.8 you can constrain the capture with infer X extends Type. If the constraint is number, boolean, or bigint, TypeScript parses the captured text and gives you the literal type.
type ParsePoint<S extends string> =
S extends `${infer X extends number},${infer Y extends number}`
? [X, Y]
: never;
type P = ParsePoint<"3,4">; // [3, 4]
type Q = ParsePoint<"3,four">; // neverWithout the constraint, X and Y would be the strings "3" and "4". With it, they are the numeric literal types 3 and 4, and a non-numeric part makes the whole match fail.
Distribution over unions
When the checked type is a bare type parameter, the conditional type distributes over unions. Each member of the union is matched on its own, and the results are joined.
type Domain<E extends string> = E extends `${string}@${infer D}` ? D : never;
type Domains = Domain<"[email protected]" | "[email protected]" | "invalid">;
// "example.com" | "test.org"The member "invalid" fails the match and contributes never. A union with never simply drops that member, so the failed input disappears from the result. This makes distribution a handy filter. It can also hide mistakes, because bad input produces no error. It only produces a smaller union.
Common errors
The input is `string`, not a literal
Pattern matching needs literal types. If the argument is a plain string, TypeScript has no characters to inspect.
type Head<S extends string> = S extends `${infer H}-${string}` ? H : never;
declare function head<S extends string>(s: S): Head<S>;
const a = head("user-42"); // "user"
declare const input: string;
const b = head(input); // neverstring is not assignable to ${infer H}-${string}, so the false branch runs. If your type will receive values computed at runtime, give it a fallback for the wide case.
type SafeHead<S extends string> =
string extends S ? string
: S extends `${infer H}-${string}` ? H
: never;
declare function safeHead<S extends string>(s: S): SafeHead<S>;
declare const raw: string;
const c = safeHead(raw); // stringThe check string extends S is true only when S is exactly string, so it catches the wide case before the pattern runs.
Expecting the last delimiter
As the "a=b=c" example showed, the first delimiter wins. For "archive.tar.gz", the pattern ${infer Name}.${infer Ext} gives Name as "archive" and Ext as "tar.gz". If you want the final extension, either match a fixed suffix such as ${infer Name}.gz, or write a recursive type.
Forgetting that empty captures are allowed
"-z" matches ${infer A}-${infer B} with A as "". If an empty piece is invalid for your use, add a check.
type NonEmptyHead<S extends string> =
S extends `${infer H}-${string}`
? H extends "" ? never : H
: never;
type X = NonEmptyHead<"-z">; // never
type Y = NonEmptyHead<"a-z">; // "a"Unions in the pattern
When the pattern itself contains a union, such as ${"a" | "b"}${infer Rest}, TypeScript expands it into a union of patterns. Matching against that union can give a union of captures. This works, but check the result type once with a few inputs before you rely on it.
Unused capture names
TypeScript does not complain about an unused infer name, but a name like _Rest tells the next reader that the capture is only there to make the pattern valid. You can also write ${string} when you do not need the value, as in ${infer H}-${string} earlier. Use ${string} when you do not need the capture, because it states that intent.
Choosing between infer and placeholders
You have two ways to match the same shape, and they answer different questions.
| Question | Tool |
|---|---|
| Does this string look like `<anything>-<anything>`? | Placeholder only: `S extends `${string}-${string}`` |
| What is the part before the hyphen? | `infer`: `S extends `${infer H}-${string}`` |
| Is this string a valid number? | `S extends `${number}`` |
| What number is this string? | `S extends `${infer N extends number}`` |
Use a plain placeholder when you only need a yes or no. It is simpler, and it does not create a type you never read.
Exercise
Write a type ParseRange<S> that takes a string such as "10..20" and returns the tuple [10, 20]. If the string does not have two numbers separated by "..", it should return never. What does ParseRange<"1..2..3"> give, and why?
Show answer
type ParseRange<S extends string> = S extends ${infer From extends number}..${infer To extends number} ? [From, To] : never;
ParseRange<"10..20"> is [10, 20]. For "1..2..3", From takes the text before the first "..", which is "1". To takes the rest, "2..3". The text "2..3" is not a valid number, so the extends number constraint fails and the result is never. Without the number constraints, the result would have been ["1", "2..3"] as strings.
Exercise
Given type Ext<S extends string> = S extends ${string}.${infer E} ? E : never;, what are Ext<"photo.png"> and Ext<"backup.tar.gz">? Which one is probably not what the author wanted, and which rule explains it?
Show answer
Ext<"photo.png"> is "png". Ext<"backup.tar.gz"> is "tar.gz", not "gz". The first ${string} placeholder is followed by the literal ".", so it takes the shortest match up to the first dot (rule 1). The last infer, E, then takes all the remaining text. To get "gz" you need a recursive type that keeps splitting, or a fixed-suffix pattern like ${string}.gz.