TypeScript Reference ยท Type Operators
TypeScript infer with extends constraints
Reference for infer U extends X in TypeScript 4.7+: constrain inferred types in conditional types, parse string literals to numbers and avoid nested conditionals.
Since TypeScript 4.7 an infer declaration can carry its own constraint: infer U extends string. The inference succeeds only when the matched part is assignable to the constraint; otherwise the whole pattern fails to match and the false branch is taken.
Before this syntax, you had to infer U freely and then nest a second conditional to test it. The constrained form is shorter, and it has one special power: when the constraint is a primitive such as number, boolean or bigint, a matched string literal can be turned into that literal type.
type FirstNum<T> = T extends [infer N extends number, ...unknown[]] ? N : never;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type Name<T> = T extends Pattern<infer U extends Constraint> ? U : Fallback;
| Part | Description |
|---|---|
infer U extends Constraint |
Declares U and requires it to be assignable to Constraint. |
| Constraint | Any type. Primitive constraints (number, bigint, boolean) in a template literal also parse the text. |
Edge cases:
- A failed constraint does not produce an error; the pattern simply does not match.
${infer N extends number}accepts only strings that round-trip exactly:"42"becomes42, but"042"or"1e3"stay unmatched.- In some positions, such as the return type of a function pattern,
infer R extends string ? A : Bis ambiguous with the outer conditional and fails to parse. Wrap the declaration in parentheses:() => (infer R extends string) ? R : never. - Without a primitive constraint,
${infer S}just captures astringslice.
Usage notes
- Less nesting. It replaces the "infer, then test" pair with one clause.
- Better results. A constraint lets the inferred variable be used where the constraint is required, with no further narrowing.
- Literal parsing enables type-level parsers: route params, size strings, version numbers.
- Check negative numbers:
"-5"matchesnumber. Whitespace around digits does not. - Version note: TypeScript 4.7 and later (TypeScript 7 supports it).
- The feature is compile-time only.