Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readTypeScript
#TypeScript#Generics#Advanced
3D illustration of a nested generic promise capsule being scanned by a glowing infer sensor that extracts the resolved inner type

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

  • infer is a declaration of a type variable scoped to one conditional type branch; it cannot be used in a type alias body outside extends.
  • The match is structural and evaluated at compile time. There is no runtime counterpart and no cost beyond type checking.
  • Position matters: infer R in 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> : never map over a union instead of treating a union as one type.
  • Multiple infer clauses 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 infer are 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 satisfy U.

Basic syntax and type signatures

typescript
// 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>; // string

The 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

PatternCapturesExample inputResult
T extends (infer R)[] ? R : neverelement of a mutable arrayboolean[]boolean
T extends readonly (infer R)[] ? R : neverelement of any arrayreadonly string[]string
T extends (...args: infer P) => any ? P : neverfull parameter tuple(a: 1, b: 2) => void[a: 1, b: 2]
T extends (a: infer A, b: infer B) => any ? [A, B] : neverparameters by position(x: 1, y: 2) => void[1, 2]
T extends Promise<infer U> ? U : neverresolved value, one levelPromise<number>number
T extends { a: infer A } ? A : neverproperty by key{ a: Date }Date
T extends Record<string, infer V> ? V : neverall property values{ a: 1; b: 2 }1 | 2
T extends infer U extends string ? U : nevercapture 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

typescript
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

typescript
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

typescript
// 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">; // number

Each 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

typescript
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

typescript
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 symptomCauseFix
'infer' declarations are only permitted in the 'extends' clause of a conditional typeinfer used in a plain alias or an intersectionmove the capture into a conditional type
Type 'X' does not satisfy the constraint on a recursive aliasrecursion on a type that is not structurally decreasingadd a readonly unknown[] accumulator or a depth tuple
Result is never for a readonly array inputthe pattern used (infer R)[]add readonly to the pattern
Union member disappears from the resultthe member failed the extends matchadd a fallback branch returning T
Whole union treated as one typethe type parameter was wrapped ([T] extends [U])use a naked type parameter to distribute
Type instantiation is excessively deep and possibly infiniteunguarded recursion over a wide inputadd a base case or an explicit depth parameter
infer name used twice yields an unexpected unionduplicate names in one pattern infer to a common supertypeuse distinct names and combine them in the branch
Overloaded method yields only its last signatureconditional types see the last overloadmodel 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 tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.