Sub topic 12
Extracting Types with infer
This chapter assumes you know generic type parameters, extends constraints, and basic conditional types (T extends U ? X : Y). You should also be comfortable with function types, tuples, and unions.
What infer does
A conditional type can test whether a type matches a pattern. The infer keyword adds a capture: inside the pattern, you give a name to a position, and TypeScript fills it in with whatever type sits there. You can then use that name in the true branch.
type ElementType<T> = T extends (infer U)[] ? U : T;
type A = ElementType<string[]>; // string
type B = ElementType<number>; // number (pattern did not match, falls to T)When T is string[], TypeScript matches it against (infer U)[] and solves for U, which is string. When T is number, the pattern fails and the false branch runs.
Think of infer U as a type parameter that is declared locally and solved by matching, not supplied by the caller.
Where infer is allowed
infer is valid only inside the extends clause of a conditional type. The inferred name is in scope only in the true branch. Using it elsewhere is a compile error.
// Error: 'infer' declarations are only permitted in the 'extends' clause
// of a conditional type.
// type Bad<T> = (infer U)[];Extracting from functions
The built-in ReturnType and Parameters are written with infer. Here are simplified versions:
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type MyParameters<T extends (...args: any) => any> =
T extends (...args: infer P) => any ? P : never;
function createUser() {
return { id: 1, name: "Ada" };
}
function send(to: string, retries: number): void {}
type User = MyReturnType<typeof createUser>; // { id: number; name: string }
type SendArgs = MyParameters<typeof send>; // [to: string, retries: number]Two details matter here:
infer Pin a rest position captures the whole parameter list as a tuple, including parameter names and optional markers.anyin the pattern is deliberate. A function type with parametersunknown[]would not accept functions that take specific arguments, because parameters are checked contravariantly.any[]makes the pattern match every function.
The false branch is never because a non-function has no return type. You could choose another fallback such as unknown, but never makes misuse visible.
Extracting from tuples
Tuple patterns let you write list operations at the type level.
type First<T extends unknown[]> = T extends [infer H, ...unknown[]] ? H : never;
type Last<T extends unknown[]> = T extends [...unknown[], infer L] ? L : never;
type Tail<T extends unknown[]> = T extends [unknown, ...infer R] ? R : never;
type F = First<[string, number, boolean]>; // string
type L = Last<[string, number, boolean]>; // boolean
type T = Tail<[string, number, boolean]>; // [number = First<[]>; // never (empty tuple does not match)First<[]> retur` has no first element, so the pattern does not match and the false branch runs.
Extracting from strings
Template literal types accept infer too. The captured part is a string literal type.
type ExtractId<T> = T extends `user-${infer Id}` ? Id : never;
type I1 = ExtractId<"user-42">; // "42"
type I2 = ExtractId<"admin-7">; // neverRecursion with infer
A conditional type can refer to itself in the true branch. This lets you peel off layers until nothing is left to unwrap.
type UnwrapPromise<T> = T extends Promise<infer U> ? UnwrapPromise<U> : T;
type X = UnwrapPromise<Promise<Promise<number>>>; // number
type Y = UnwrapPromise<string>; // stringEach step captures the inner type U and calls the same type again on it. The recursion ends when T is no longer a Promise. In real code, prefer the built-in Awaited<T>, which also handles objects with a then method.
Several infer positions for one name
You can use the same name in more than one position. How TypeScript combines the candidates depends on where the name appears.
- In covariant positions (such as properties and return types), the candidates are combined as a union.
- In contravariant positions (such as function parameters), the candidates are combined as an intersection.
type FromProps<T> = T extends { a: infer U; b: infer U } ? U : never;
type P1 = FromProps<{ a: string; b: number }>; // string | number
type FromParams<T> = T extends {
a: (x: infer U) => void;
b: (x: infer U) => void;
}
? U
: never;
type P2 = FromParams<{
a: (x: { id: number }) => void;
b: (x: { name: string }) => void;
}>; // { id: number } & { name: string }The intersection result makes sense. A single value that can be passed to both functions must satisfy both parameter types. This behavior is the basis of the well-known "union to intersection" type trick.
Constraining an inferred type
Since TypeScript 4.7, an inferred variable can have its own extends constraint. The pattern then matches only if the captured type satisfies it.
type FirstString<T> = T extends [infer S extends string, ...unknown[]]
? S
: never;
type F1 = FirstString<["a", 1]>; // "a"
type F2 = FirstString<[1, "a"]>; // never (first element is not a string)Before this feature, you needed a second conditional type to check the captured value:
type FirstStringOld<T> = T extends [infer S, ...unknown[]]
? S extends string
? S
: never
: never;The constrained form is shorter and keeps the intent in one place. Note that it needs TypeScript 4.7 or later. On older versions, use the nested form.
Gotchas
Distribution over unions
When the checked type is a bare type parameter, a conditional type distributes over a union. This applies to infer patterns too.
type ElementType<T> = T extends (infer U)[] ? U : T;
type D1 = ElementType<string[] | number[]>; // string | number
type D2 = ElementType<string[] | boolean>; // string | booleanIn D2, string[] matches and gives string. boolean does not match and falls through as itself. If you need the union checked as a whole, wrap both sides in tuples: [T] extends [(infer U)[]].
Overloaded functions
When a function has overloads, infer sees only the last signature.
declare function parse(x: string): number;
declare function parse(x: number): string;
type R = ReturnType<typeof parse>; // string (from the last overload)TypeScript cannot capture all overloads at once. If you rely on ReturnType or Parameters for an overloaded function, check which signature is last.
Methods and `this`
If the function type has a this parameter, a pattern like (...args: infer P) => any ignores it. Use ThisParameterType for that part.
Unresolved results
If TypeScript cannot narrow the captured variable, it falls back to its constraint, or to unknown when there is none. A result of unknown often means the pattern is too loose, and a result of never often means it never matched.
Cost of deep recursion
Recursive conditional types are checked at compile time and have a depth limit. Very long tuples or deeply nested types can hit the "Type instantiation is excessively deep" error. Keep recursive patterns simple, and prefer built-ins such as Awaited when they exist.
Summary of patterns
| Goal | Pattern |
|---|---|
| Array element | `T extends (infer U)[] ? U : never` |
| Return type | `T extends (...args: any[]) => infer R ? R : never` |
| Parameter list | `T extends (...args: infer P) => any ? P : never` |
| Promise value | `T extends Promise<infer U> ? U : never` |
| Tuple head | `T extends [infer H, ...unknown[]] ? H : never` |
| Tuple tail | `T extends [unknown, ...infer R] ? R : never` |
| String piece | ``T extends `prefix-${infer Rest}` ? Rest : never`` |
Exercise
Write a type AsyncResult<T> that takes an async function type and gives the type its promise resolves to. For example, given async function load(): Promise<string[]>, AsyncResult<typeof load> should be string[]. What does AsyncResult<() => number> produce with your definition?
Show answer
Use type AsyncResult<T> = T extends (...args: any[]) => Promise<infer R> ? R : never; The pattern requires a function that returns a Promise and captures the resolved type R, so AsyncResult<typeof load> is string[]. For () => number, the return type is not a Promise, so the pattern does not match and the result is never.