TypeScript Reference ยท Type Operators
The infer keyword in TypeScript
Reference for infer in TypeScript conditional types: capture return types, parameters, array elements and promise values, with multiple candidates and edge cases.
infer declares a new type variable inside the extends clause of a conditional type. The compiler fills the variable in by matching the checked type against the pattern, and you can then use it in the true branch.
That is how ReturnType, Parameters and Awaited are built: describe the shape you expect, mark the part you care about with infer, and let the compiler extract it. infer is only valid inside the extends clause of a conditional type.
type Elem<T> = T extends (infer E)[] ? E : never; type N = Elem<number[]>; // number
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> ? UsesU : Fallback;
| Part | Description |
|---|---|
infer U |
Introduces U, scoped to the true branch only. |
Pattern<...> |
Any type shape: function, array, tuple, object, promise, template literal. |
| Fallback | Used when T does not match the pattern (often never or T). |
Edge cases:
- If the same
infer Uappears in several covariant positions, candidates are unioned. In contravariant positions (function parameters) they are intersected. - Inferring from an overloaded function uses the last signature.
- A generic function is inferred with its type parameters replaced by their constraints (often
unknown). - If nothing can be inferred,
Ubecomesunknown.
Usage notes
- Scope:
Udoes not exist in the false branch or outside the conditional. - Constrain it with
infer U extends Xto avoid extra conditionals. - Recursion with
inferover tuples and template literals is the base of type-level parsing (split, join, trim). - Tuples:
[infer H, ...infer T]peels the first element;[...infer I, infer L]the last. - Objects: match property by property, e.g.
{ data: infer D }. Optional or readonly modifiers must be compatible with the pattern. - Distribution: if
Tis a naked type parameter holding a union, each member is matched separately; see distributive conditional types. - Readability: give inferred names meaningful letters (
Rfor return,Pfor parameter) in complex types. - Zero runtime cost; it is erased.