Codectionary / Developer documentation / TypeScript

The infer Keyword

infer, used only within the extends clause of a conditional type, lets you declare a new type variable that captures part of a matched structure, so it can be reused in the result. It is the mechanism behind utility types like ReturnType<T> and Parameters<T>, which extract specific pieces of a function's type signature.

Syntax

T extends SomePattern<infer U> ? U : never

Examples

Extracting a Function's Return Type

A simplified version of how TypeScript's built-in ReturnType<T> actually works.

type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

function getUser() {
  return { id: 1, name: "Alice" };
}

type User = MyReturnType<typeof getUser>;
// User is inferred as: { id: number; name: string }

Extracting an Array's Element Type

Unwrapping the inner type from an array or Promise.

type ElementType<T> = T extends (infer Item)[] ? Item : never;

type A = ElementType<string[]>; // string
type B = ElementType<number[]>; // number

type UnwrapPromise<T> = T extends Promise<infer Value> ? Value : T;
type C = UnwrapPromise<Promise<string>>; // string

Best practices

  • Use infer specifically when you need to extract and reuse a piece of a matched type, rather than just checking whether it matches
  • Study infer through TypeScript's built-in utility types (ReturnType, Parameters, Awaited) - they are the clearest real-world examples of this pattern
  • Remember infer can only appear within the extends clause of a conditional type - it has no meaning outside that specific context
  • Keep infer-based types well-named and documented, since the syntax itself is dense and can be hard to parse at a glance for readers unfamiliar with it

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation