# infer

> The `infer` keyword in TypeScript declares a type variable inside a conditional type to capture a type.

## How does the infer keyword work in TypeScript conditional types?

The keyword used in the `extends` clause of a conditional type to introduce a type variable that TS infers from the checked type. For example, it extracts the element type of an array or the return type of a function.

- Topic: Syntax
- Type: keyword

## Example

Wrong:

```ts
type ElementOf<T> = T extends any[] ? any : never;
type X = ElementOf<string[]>;
```

Right:

```ts
type ElementOf<T> = T extends (infer U)[] ? U : never;
type X = ElementOf<string[]>;
```

`infer U` captures the array element type, so `X` is `string` instead of `any`.

## Common mistakes

- Getting a union result because the conditional type distributes over a union input.

## Key points

- `infer` appears only in the `extends` clause of a conditional type.
- Built-in helpers like `ReturnType`, `Parameters` and `Awaited` are used instead of hand-written `infer` copies.
- Captured types are constrained when needed, e.g. `infer U extends string`.

## Interview questions

### Can I use infer outside a conditional type?

No, `infer` is only allowed in the `extends` clause of a conditional type.

### How do I stop a conditional type from distributing over a union?

Wrap both sides in brackets: `[T] extends [U] ? X : Y`. The check then runs once on the whole union.

## Related cards

- [Conditional Types](https://wonderium.dev/ts/conditional-types.md)
- [`ReturnType<T>`](https://wonderium.dev/ts/returntype.md)
- [`Awaited<T>`](https://wonderium.dev/ts/awaited.md)
- [`Parameters<T>`](https://wonderium.dev/ts/parameters.md)
- [Template Literal Types](https://wonderium.dev/ts/template-literal-types.md)

---

- Level: [TypeScript](https://wonderium.dev/ts.md)
- HTML version: https://wonderium.dev/ts/infer
- Last updated: 2026-11-25
