TypeScript infer Keyword: Conditional Types, ReturnType, and Unwrapping
How infer binds a type inside a conditional type, why distribution over unions changes results, and how ReturnType, Parameters, and recursive unwrapping types are actually built.

infer is the only way to name a type that TypeScript has already matched but does not expose. It appears nowhere except inside the extends clause of a conditional type: the compiler checks whether a type matches a pattern, and every infer X in that pattern binds a name to whatever that position held. ReturnType, Parameters, Awaited, and most of the utility types shipped with the language are written this way, and writing your own is a matter of knowing which positions of a pattern can capture.
Quick Summary
inferis a declaration of a type variable scoped to one conditional type branch; it cannot be used in a type alias body outsideextends.- The match is structural and evaluated at compile time. There is no runtime counterpart and no cost beyond type checking.
- Position matters:
infer Rin the return position captures the return type, in a tuple element it captures that element, and in a function parameter it captures the parameter type. - A conditional type distributes over naked union type parameters by default, which is what makes
T extends any ? F<T> : nevermap over a union instead of treating a union as one type. - Multiple
inferclauses in one pattern bind independently, and the same name used twice in one pattern becomes an inference to a common supertype, which is rarely what you want. - Recursive conditional types (TypeScript 4.1+) with
inferare how nested structures are unwrapped, and depth limits are enforced by the compiler with a tail-recursion allowance in 4.5+. infer X extends U(4.7+) constrains the capture and fails the match when the captured type does not satisfyU.
Basic syntax and type signatures
// The canonical shape: a conditional type with a captured position.
type ElementType<T> = T extends readonly (infer U)[] ? U : never;
type A = ElementType<string[]>; // string
type B = ElementType<readonly [1, 2]>; // 1 | 2
type C = ElementType<number>; // never
// Function shapes: capture parameters and return.
type MyReturn<T> = T extends (...args: any[]) => infer R ? R : never;
type MyParams<T> = T extends (...args: infer P) => any ? P : never;
type R1 = MyReturn<(a: string, b: number) => boolean>; // boolean
type R2 = MyParams<(a: string, b: number) => boolean>; // [a: string, b: number]
// Object shape: capture a property type by pattern.
type PropType<T, K extends keyof T> = T extends Record<K, infer V> ? V : never;
type R3 = PropType<{ id: number; name: string }, "name">; // string
// Promise unwrapping, one level.
type Unwrap<T> = T extends Promise<infer U> ? U : T;
type R4 = Unwrap<Promise<number>>; // number
type R5 = Unwrap<string>; // stringThe built-in ReturnType<T> is exactly MyReturn<T> above; reading the shipped utility type definition is the fastest way to learn the syntax, because the library types are small, explicit, and use every feature of the construct.
Comparison of capture patterns
| Pattern | Captures | Example input | Result |
|---|---|---|---|
T extends (infer R)[] ? R : never | element of a mutable array | boolean[] | boolean |
T extends readonly (infer R)[] ? R : never | element of any array | readonly string[] | string |
T extends (...args: infer P) => any ? P : never | full parameter tuple | (a: 1, b: 2) => void | [a: 1, b: 2] |
T extends (a: infer A, b: infer B) => any ? [A, B] : never | parameters by position | (x: 1, y: 2) => void | [1, 2] |
T extends Promise<infer U> ? U : never | resolved value, one level | Promise<number> | number |
T extends { a: infer A } ? A : never | property by key | { a: Date } | Date |
T extends Record<string, infer V> ? V : never | all property values | { a: 1; b: 2 } | 1 | 2 |
T extends infer U extends string ? U : never | capture with a constraint | "x" | "x", 1 gives never |
The difference between rows one and two is the one that bites first: T extends (infer R)[] does not match a readonly array, so a readonly string[] falls through to never. Writing readonly in the pattern makes it match both.
Practical edge cases and deep dives
1. Distribution, and the tuple wrapper that turns it off
type UnwrapPromiseDeep<T> = T extends Promise<infer U> ? UnwrapPromiseDeep<U> : T;
type D1 = UnwrapPromiseDeep<Promise<Promise<number>>>; // number
type D2 = UnwrapPromiseDeep<Promise<number> | Promise<string>>; // number | string
type D3 = UnwrapPromiseDeep<[Promise<number>, Promise<string>]>; // [number, string]
// A naked type parameter distributes over a union; a tuple does not.
type Boxed<T> = T extends any ? [T] : never;
type B1 = Boxed<"a" | "b">; // ["a"] | ["b"]
type NotBoxed<T> = [T] extends [any] ? [T] : never;
type B2 = NotBoxed<"a" | "b">; // ["a" | "b"]Distribution is a property of a naked type parameter in the extends position. Wrapping both sides in [T] extends [U] disables it, which is the standard trick when a mapped result must stay a single object. The failure it prevents is subtle: with distribution on, T extends Promise<infer U> over Promise<number> | Promise<string> produces number | string — usually what you want — but over Promise<number> | string the string branch is not a Promise, so it disappears from the result instead of passing through.
2. Function overloads, this, and the difference between the last signature and the whole set
interface Api {
get(id: string): Promise<Response>;
post(body: unknown): Promise<Response>;
}
type LastParam<T> = T extends (...args: infer P) => any
? P extends [...any[], infer L]
? L
: never
: never;
// Conditional types see only the last overload signature.
type P = LastParam<Api["get"]>; // string
// For the whole overload set, the conditional type must be applied per member.
type AllParams<T> = T extends { [K in keyof T]: infer F } ? F : never;Overloads are not visible to a conditional type: T extends (...args: infer P) => any matches the last declared signature only. If the caller needs every signature, model the API as a mapped type of function types instead of an overloaded interface, or write one conditional type per method.
3. Recursion, depth limits, and the infer-based parser
// Split a path into segments and retrieve the value type at the end of that path.
type Split<S extends string> =
S extends `${infer Head}/${infer Tail}` ? [Head, ...Split<Tail>] : [S];
type Get<T, P extends string> =
P extends `${infer K}/${infer Rest}`
? K extends keyof T
? Get<T[K], Rest>
: never
: P extends keyof T
? T[P]
: never;
interface Config {
db: { host: string; port: number };
cache: { ttl: number };
}
type H = Get<Config, "db/host">; // string
type T = Get<Config, "cache/ttl">; // numberEach recursive step consumes one template literal segment, and the recursion terminates when no / remains. TypeScript allows deep recursion up to a limit that reports Type instantiation is excessively deep and possibly infinite when exceeded; since 4.5 the compiler can reuse tail-recursive instantiations, so Split over a long string is viable where the same shape once failed. A parser should still cap the depth it accepts, because the compiler's limit is not a number you control.
4. infer X extends U and filtered captures
type FirstString<T extends readonly unknown[]> =
T extends readonly [infer H extends string, ...unknown[]] ? H : never;
type F1 = FirstString<["a", 1]>; // "a"
type F2 = FirstString<[1, "a"]>; // never — first element is not a string
// Without the constraint the capture still binds, then the branch must test it.
type FirstString2<T extends readonly unknown[]> =
T extends readonly [infer H, ...unknown[]]
? H extends string
? H
: never
: never;The inline constraint (4.7+) changes matching rather than filtering afterwards: the whole pattern fails and the false branch runs. That distinction matters in recursive types, where a failed match terminates the recursion instead of producing never deep inside it.
5. Extracting the resolved type of a chain of thenables
type AwaitedDeep<T> = T extends null | undefined
? T
: T extends object & { then(onfulfilled: infer F, ...args: infer _): any }
? F extends (value: infer V, ...args: infer _) => any
? AwaitedDeep<V>
: never
: T;
declare function resolve(): PromiseLike<PromiseLike<{ id: number }>>;
type Resolved = AwaitedDeep<ReturnType<typeof resolve>>; // { id: number }This is a simplified form of the built-in Awaited<T>, which handles thenables, not just Promise. The object & intersection keeps the match structural without requiring a nominal Promise, which is why PromiseLike values resolve too. In application code, prefer the built-in; the value of reading this shape is understanding why T extends Promise<infer U> is not enough for real libraries.
Common mistakes and compiler errors
| Error or symptom | Cause | Fix |
|---|---|---|
'infer' declarations are only permitted in the 'extends' clause of a conditional type | infer used in a plain alias or an intersection | move the capture into a conditional type |
Type 'X' does not satisfy the constraint on a recursive alias | recursion on a type that is not structurally decreasing | add a readonly unknown[] accumulator or a depth tuple |
Result is never for a readonly array input | the pattern used (infer R)[] | add readonly to the pattern |
| Union member disappears from the result | the member failed the extends match | add a fallback branch returning T |
| Whole union treated as one type | the type parameter was wrapped ([T] extends [U]) | use a naked type parameter to distribute |
Type instantiation is excessively deep and possibly infinite | unguarded recursion over a wide input | add a base case or an explicit depth parameter |
infer name used twice yields an unexpected union | duplicate names in one pattern infer to a common supertype | use distinct names and combine them in the branch |
| Overloaded method yields only its last signature | conditional types see the last overload | model the API as a mapped type |
The practical rule is to write the smallest conditional type that answers one question and compose several of them, rather than one pattern that captures everything at once. A composed chain produces a readable error at the step that failed, while a single deep pattern reports never and leaves you to guess which position stopped matching.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
TypeScript Branded Types: Nominal Typing, Type Tags, and Validation
How a phantom property makes two strings incompatible, unique symbol brands, unit-typed numbers, and the places where a brand quietly disappears.
TypeScript Ambient Declarations: .d.ts Files, declare, and declare global
How declare and .d.ts files describe runtime values, wildcard modules for assets, declare global with var, and module augmentation of third-party types.
TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type
Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.