Understanding the infer Keyword in TypeScript

Hemanta Sundaray

Published December 30, 2023


In TypeScript, the infer keyword is used within the context of conditional types. It allows you to declare a generic type variable (a placeholder for a type that is specified when the generic is used) within the condition itself.

What are Conditional Types?

These are types that depend on a condition. They typically have the form T extends U ? X : Y, where T is a type that is checked against type U. If T extends U, type x is used; otherwise, type Y is used.

infer Keyword Example

Let’s consider an example to understand how infer works.

type ElementType<T> = T extends (infer U)[] ? U : never;
 
type A = ElementType<number[]>; // number

In this example:

The advantage of using infer is that it allows the type to be inferred automatically without the need to explicitly define all generic parameters upfront. This leads to more concise and flexible types.