Sub topic 3
Capturing a Type with `infer`
This chapter assumes you know TypeScript generics, unions, intersections, tuples, mapped types, function signatures, and basic template literal types. You will use those features to inspect an existing type and capture one of its parts.
What `infer` does
A conditional type chooses between two types:
type Result<T> = T extends string ? "text" : "other";The expression before ? asks whether T matches string. If it does, the result is "text". Otherwise, the result is "other".
The infer keyword declares a temporary type variable inside the matching pattern. TypeScript fills in that variable when the input matches.
type ElementType<T> = T extends (infer U)[] ? U : never;
type A = ElementType<string[]>; // string
type B = ElementType<number[]>; // number
type C = ElementType<number>; // neverFor string[], TypeScript matches the pattern (infer U)[] and assigns string to U. The true branch returns U.
The inferred variable exists only in the true branch. You cannot use U in the false branch or outside the conditional type.
Reading an `infer` pattern
The location of infer determines what TypeScript captures.
| Pattern | Captured type |
|---|---|
| `(infer U)[]` | The array element type |
| `(...args: any[]) => infer R` | The return type |
| `(...args: infer P) => any` | The parameter tuple |
| `PromiseLike<infer U>` | The promised value type |
| `[infer First, ...unknown[]]` | The first tuple element |
For example, a function return type can be captured like this:
type MyReturnType<T> =
T extends (...args: any[]) => infer R ? R : never;
function makeUser(name: string, age: number) {
return { name, age };
}
type User = MyReturnType<typeof makeUser>;
// { name: string; age: number }typeof makeUser produces the function type. The pattern matches any function, and infer R captures its return type.
You can capture the complete parameter list instead:
type MyParameters<T> =
T extends (...args: infer P) => any ? P : never;
type Arguments = MyParameters<typeof makeUser>;
// [name: string, age: number]Here, P is a tuple containing the function's parameter types.
Matching nested structures
The pattern can contain several inferred variables:
type FirstAndRest<T> =
T extends [infer First, ...infer Rest]
? { first: First; rest: Rest }
: never;
type Parts = FirstAndRest<[string, number, boolean]>;
// { first: string; rest: [number, boolean] }The tuple must have at least one element. First captures the first element, while Rest captures the remaining tuple.
You can also add a constraint to an inferred variable. This makes the pattern match only when the captured type meets that constraint.
type FirstString<T> =
T extends [infer S extends string, ...unknown[]] ? S : never;
type Good = FirstString<["ready", 200]>; // "ready"
type Bad = FirstString<[200, "ready"]>; // neverThe first tuple matches because its first element extends string. The second tuple fails because its first element is number.
A useful mental model
When reading an infer utility, follow these steps:
- Find the conditional type's input.
- Read the pattern after
extends. - Identify each
infervariable. - Substitute the matching parts into the true branch.
- Use the false branch when the shape does not match.
infer does not create a runtime value and does not change JavaScript output. It only helps the compiler calculate a type.
type ElementType<T> = T extends (infer U)[] ? U : never;
const names: ElementType<string[]>[] = ["Ada", "Lin"];
// The variable is string[] at compile time.Exercise
What is the result of type R = MyReturnType<() => Date> when MyReturnType<T> = T extends (...args: any[]) => infer U ? U : never?
Show answer
R is Date, because infer U captures the function's return type.