# The infer Keyword

> Extracting inner types from inside complex types.

Subject: TypeScript | Lesson 29 of 54 | 5 min read
Interactive lesson: https://codewithanimation.in/typescript/infer-keyword
Previous: [Conditional Types](https://codewithanimation.in/typescript/conditional-types.md) | Next: [Mapped Types](https://codewithanimation.in/typescript/mapped-types.md)

## 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
```

## Common mistake: Strict Placement Rules

The `infer` keyword has a strict grammatical rule: It can ONLY be used inside the `extends` clause of a conditional type.

You cannot use `infer` anywhere else in TypeScript. It is intrinsically tied to ternary conditionals.

## Tip: Built-in Utilities

TypeScript actually ships with built-in utility types that use `infer` under the hood! Examples include `ReturnType<T>`, `Parameters<T>`, and `Awaited<T>`.

## Try it: Try it

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

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/infer-keyword

## Check yourself

### Question 1

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

- A. { id: number, name: string }
- B. number
- C. never

Correct answer: B

The conditional checks if T has an 'id' property. If it does, it infers its type into U (which is 'number'), and returns U.

- Why not A: The 'infer U' only extracts the specific type mapped to the 'id' property.
- Why not C: The object does have an 'id' property, so the true branch evaluates, returning the inferred type.

## 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.
