The infer Keyword

Extracting inner types from inside complex types.

TypeScript5 min readConcept 29 of 54

Surgical Type Extraction

The infer keyword allows you to reach inside a complex type and extract a specific inner type into a new, temporary type variable.

It is most commonly used to unwrap types, like getting the item type out of an Array, or getting the return type out of a Function.

Dealing with Black Boxes

Sometimes a third-party library gives you a function fetchUser(): Promise<User>, but they forgot to export the User type itself!

Instead of redefining User manually, you can use infer to "reach into" the Promise and extract the User type dynamically.

Syntax

typescript // "If T is an Array of some type R, give me R. Otherwise, give me T." type UnpackArray<T> = T extends Array<infer R> ? R : T; type A = UnpackArray<string[]>; // string type B = UnpackArray<number>; // number // "If T is a function returning some type R, give me R." type GetReturn<T> = T extends (...args: any[]) => infer R ? R : never; type C = GetReturn<() => boolean>; // boolean

Try it

Watch how the infer R keyword physically reaches into the Array<string> wrapper and yanks out the inner string type.

Unpack:
type Unpack<T> =TextendsArray<inferR>?R:T;

// Caller
type Res = Unpack<string[]>;
Type Extractor Engine
Array
string
infer R
Extracted string into R!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Given `type Extract<T> = T extends { id: infer U } ? U : never`, what is `Extract<{ id: number, name: string }>`?

Remember this

  • infer R declares a temporary type variable R to capture an inner type.
  • It can ONLY be used inside the extends clause of a conditional type.
  • It is incredibly useful for unwrapping Arrays, Promises, and Functions.
  • If the extraction succeeds, you can return R in the true branch of the conditional.

Done with this concept?

Mark it complete to track your progress. No login needed.