← TypeScript

Advanced · 2 of 12 · 13 min read

The infer keyword

Pattern matching for types — how infer names a piece of a shape you matched, where multiple candidates come from, and how it is used to write ReturnType from scratch.

  • infer

infer is destructuring for types. It appears inside the extends clause of a conditional, marks a hole in a pattern, and binds whatever filled that hole to a name you can use in the true branch.

The smallest useful example

type Unwrap<T> = T extends Promise<infer Payload> ? Payload : T;

type A = Unwrap<Promise<string>>;  // string
type B = Unwrap<number>;           // number

const a: A = "x";
const b: B = 1;
console.log(a, b);

Compare it to doing the same thing without infer, which you cannot: there is no T["payload"] to index into, and no way to name the type argument a generic was given. infer is the only way to get at it.

Writing the standard library

Three of the utility types are one conditional each:

type MyReturnType<F> = F extends (...args: never[]) => infer R ? R : never;
type MyParameters<F> = F extends (...args: infer P) => unknown ? P : never;
type MyAwaited<T> = T extends Promise<infer R> ? MyAwaited<R> : T;

function createUser(name: string, age: number) {
  return { id: 1, name, age };
}

type User = MyReturnType<typeof createUser>;    // { id: number; name: string; age: number }
type Args = MyParameters<typeof createUser>;    // [name: string, age: number]
type Deep = MyAwaited<Promise<Promise<number>>>; // number

const args: Args = ["Ana", 30];
const user: User = createUser(...args);
const deep: Deep = 1;
console.log(user.name, deep);

MyParameters infers a tuple out of a rest parameter, which is where the parameter names in the result come from. MyAwaited recurses, matching what await does with a promise of a promise.

The never[] in MyReturnType is deliberate, and worth being able to explain: parameters are contravariant, so the most permissive pattern for “any function at all” uses never in parameter position. any[] also works and is what the real ReturnType uses; unknown[] is the one that fails, because a function taking a string is not assignable to one taking unknown.

Matching anything with a shape

The pattern can be as specific as you need:

type ElementOf<T> = T extends readonly (infer Item)[] ? Item : never;
type First<T> = T extends readonly [infer Head, ...unknown[]] ? Head : never;
type Last<T> = T extends readonly [...unknown[], infer Tail] ? Tail : never;
type Rest<T> = T extends readonly [unknown, ...infer Tail] ? Tail : never;

type Row = [string, number, boolean];

type A = ElementOf<Row>;  // string | number | boolean
type B = First<Row>;      // string
type C = Last<Row>;       // boolean
type D = Rest<Row>;       // [number, boolean]

const d: D = [1, true];
console.log(d);

First, Last and Rest together are head/tail on a tuple, which is what makes recursive type-level list processing possible.

It works on object shapes and on class constructors too:

type PropType<T> = T extends { value: infer V } ? V : never;
type Instance<C> = C extends new (...args: never[]) => infer I ? I : never;

class Widget { render() { return "x"; } }

type A = PropType<{ value: Date }>;  // Date
type B = Instance<typeof Widget>;    // Widget

const b: B = new Widget();
console.log(b.render());

Multiple candidates

Two infer R in the same pattern do not conflict — the compiler collects both candidates and combines them, and which way it combines depends on the position:

type BothParams<F> = F extends (a: infer T, b: infer T) => unknown ? T : never;
type BothReturns<F> = F extends { (): infer T; (x: string): infer T } ? T : never;

type A = BothParams<(a: string, b: number) => void>;  // string & number -> never
type B = BothReturns<{ (): string; (x: string): number }>; // string | number

const b: B = "x";
console.log(b);

Covariant positions (a return) produce a union; contravariant positions (a parameter) produce an intersection. string & number is never, which is why the first one looks broken and is in fact consistent: a single type that could be passed as both parameters does not exist.

Pattern Infers
Promise<infer R> the payload
(...args: infer P) => unknown the parameters, as a tuple
(...args: never[]) => infer R the return type
readonly (infer Item)[] the element type
[infer Head, ...unknown[]] the first element
[...unknown[], infer Tail] the last element
new (...args: never[]) => infer I the instance type
{ value: infer V } one property’s type
`${infer A}-${infer B}` the parts of a string literal

Constrained infer

A constraint on the inferred position filters the match instead of widening it:

type FirstString<T> = T extends readonly [infer Head extends string, ...unknown[]]
  ? Head
  : "not a string";

type A = FirstString<["id", 1]>;  // "id"
type B = FirstString<[1, "id"]>;  // "not a string"

const a: A = "id";
const b: B = "not a string";
console.log(a, b);

Before infer X extends Y existed, the same thing needed a nested conditional. It also narrows the inferred type, which matters when the result feeds a template literal type that requires a string.

Recursion over a tuple

With head/tail and a base case, the type system is a small functional language:

type Reverse<T extends readonly unknown[]> = T extends readonly [infer Head, ...infer Tail]
  ? [...Reverse<Tail>, Head]
  : [];

type Join<T extends readonly string[], Sep extends string> =
  T extends readonly [infer Head extends string, ...infer Tail extends string[]]
    ? Tail extends readonly []
      ? Head
      : `${Head}${Sep}${Join<Tail, Sep>}`
    : "";

type A = Reverse<[1, 2, 3]>;              // [3, 2, 1]
type B = Join<["a", "b", "c"], "/">;      // "a/b/c"

const a: A = [3, 2, 1];
const b: B = "a/b/c";
console.log(a, b);

The base case is the empty tuple, and Tail extends readonly [] is the “last element” test that keeps the separator out of the end. The recursion limit is around 1000 instantiations deep, which is far more than a real tuple needs and far less than a loop over characters of a long string.

Where it is not allowed

// type Bad<T> = infer R;                          // not in a conditional
// type Also<T> = T extends Promise<infer R> ? T : R;  // R is not in scope here
type Fine<T> = T extends Promise<infer R> ? R : never;

const fine: Fine<Promise<number>> = 1;
console.log(fine);

One place, one scope: the extends clause, and the true branch. Everything built with infer works around that restriction rather than escaping it.

Common mistakes

Using the inferred name in the false branch

Mistake. T extends Promise<infer R> ? T : R. Why it fails. R only exists where the match succeeded. In the false branch there was no match, so there is nothing to name. What to do instead. Return T or never from the false branch.

unknown[] as the catch-all parameter pattern

Mistake. F extends (...args: unknown[]) => infer R. Why it fails. Parameters are contravariant: a function taking a string is not assignable to one taking unknown, so concrete functions fail to match and the result is never. What to do instead. never[] or any[] in that position.

Recursing without a base case that the compiler can reach

Mistake. A recursive conditional whose termination depends on a type the compiler defers. Why it fails. “Type instantiation is excessively deep and possibly infinite” — and the type becomes any, so everything downstream silently stops being checked. What to do instead. Match the empty tuple or the exhausted string explicitly, and keep recursion to shapes with a known length.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

What does infer do inside a conditional type?

Several infer positions can appear in one pattern, including in a tuple.

What does First<[string, number, boolean]> resolve to?

Code sample
type First<T> = T extends [infer F, ...infer _Rest] ? F : never;

What does infer R extends string add?

Practise infer →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.