How type argument inference works

Advanced · 26 min

How TypeScript picks type arguments from a call's inference sites, why callbacks are inferred last, and how `NoInfer` stops an argument from widening `T`.

Before thisWhy generics, and generic functionsGeneric constraintsGeneric defaults and const type parameters

JavaScript Conferences by GitNation · 26 min

How type argument inference works

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by JavaScript Conferences by GitNationReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Every place a type parameter appears in a parameter's type is an inference site; at a call, TypeScript matches each argument's type against its parameter's type and collects candidates for each type parameter.
  • When several sites produce different candidates, the compiler tries to settle on one of them rather than inventing a union, so `same(n, s)` with a `number` and a `string` is an error, not `T = string | number`.
  • Arguments whose type depends on context, mostly arrow functions with unannotated parameters, are inferred in a later pass, after the other arguments have fixed the type parameters they need.
  • If nothing can be inferred, a type parameter falls back to its default, then to its constraint, then to `unknown`.
  • Explicit type arguments are all or nothing: you can't specify the first and let the rest be inferred, unless the rest have defaults.
  • `NoInfer<T>`, added in TypeScript 5.4, marks a parameter as one that must be checked against `T` but must not help decide what `T` is.

Why look inside inference at all

Most of the time inference just works, and you never write a type argument. Then one day it infers unknown, or a union you didn’t expect, or a callback parameter becomes any-shaped in a way that makes no sense. Those moments are much easier to fix with a model of what the compiler is actually doing. The model doesn’t need to be exact; it needs to predict the cases that surprise people.

Inference sites and candidates

When you call a generic function without type arguments, the compiler lines up each argument against its parameter’s type and looks for the type parameters inside. Each place a type parameter appears is an inference site:

function map<T, U>(items: T[], fn: (item: T) => U): U[] {
  return items.map(fn);
}

Here T has two sites, items: T[] and the callback’s parameter, and U has one, the callback’s return type. Matching string[] against T[] produces the candidate string for T. The compiler collects candidates from every site, then picks a type for each parameter.

Picking is where people’s intuition diverges from the compiler’s. It doesn’t union candidates together:

function same<T>(a: T, b: T): T {
  return a;
}

declare const n: number;
declare const s: string;

const both = same(1, 2); // number
same(n, s);
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.

With number and string as candidates, the compiler looks for one candidate the others are assignable to. There isn’t one, so it settles on the first and reports the other argument. That’s deliberate: two parameters typed T usually mean “these should match”, and silently unioning would hide the mistake. If you do want both, write same<number | string>(n, s).

Notice same(1, 2) gave number, not 1 | 2. Literal candidates are widened unless something, such as a const type parameter or a primitive constraint, says to keep them.

Context-sensitive arguments go last

Arrow functions with unannotated parameters can’t be typed on their own: (v) => v.toFixed() means nothing until you know what v is. The compiler calls these context-sensitive, and it handles them in a later pass:

function pipe<T, U>(value: T, fn: (v: T) => U): U {
  return fn(value);
}

const out = pipe(5, (n) => n.toFixed(2)); // string

function apply<T>(fn: (v: T) => void, value: T): void {
  fn(value);
}

apply((v) => v.toFixed(), 3); // v: number, even though the callback comes first

In the first pass the compiler skips the arrows and infers from everything else, here 5 and 3, fixing T as number. In the second pass it types each arrow’s parameters from that, then reads the arrow’s return type to infer U. This is why a callback’s parameter types “just appear”, and it’s why annotating a callback parameter yourself, as in (v: number) => ..., turns it back into an ordinary inference site.

Think of a building inspector who signs off the foundation before inspecting the floors built on it. The callbacks are the floors: they can only be checked once the types they rest on are settled.

When there’s nothing to infer from

If no site produces a candidate, the type parameter falls back to its default, then to its constraint, then to unknown:

function empty<T>(): T[] {
  return [];
}

const e = empty(); // unknown[]

function emptyNames<T extends string>(): T[] {
  return [];
}

const names = emptyNames(); // string[]

There’s one more, lower-priority source: the type the call’s result is assigned to. const label: string = make() can infer T = string for function make<T>(): T. Don’t design around it, but it explains some results that seem to come from nowhere.

Explicit type arguments switch inference off entirely for that call. You can’t fill in the first and let the rest be inferred:

function convert<In, Out>(value: In, fn: (v: In) => Out): Out {
  return fn(value);
}

convert<string>("x", (s) => s.length);
// Error: Expected 2 type arguments, but got 1.

Blocking an inference site with NoInfer

Every appearance of T in a parameter is a site, and sometimes that’s wrong. Consider a state machine helper:

function createMachine<S extends string>(states: S[], initial: S) {
  return { states, current: initial };
}

createMachine(["idle", "loading"], "done"); // compiles: S is "idle" | "loading" | "done"

The author meant states to define S and initial to be checked against it. The compiler treats both as sources, so the typo "done" becomes a candidate and widens S to include itself. TypeScript 5.4 added NoInfer<T> for exactly this:

function createMachineSafe<S extends string>(states: S[], initial: NoInfer<S>) {
  return { states, current: initial };
}

createMachineSafe(["idle", "loading"], "done");
// Error: Argument of type '"done"' is not assignable to parameter of type '"idle" | "loading"'.

NoInfer<S> evaluates to S, but the compiler won’t collect candidates from inside it. Before 5.4 the common workaround was a second type parameter, <S extends string, I extends S>(states: S[], initial: I), which works but adds a parameter whose only job is to block inference.

About the video

Ryan Cavanaugh, the TypeScript team’s development lead, builds a simplified inference algorithm live from motivating examples: collecting candidates from inference sites, choosing among them, and handling context-sensitive functions in later passes. It’s a conference talk, so it moves quickly and goes deeper than this lesson. Read the sections above first and treat the talk as the explanation of why the compiler behaves this way. It predates NoInfer, so the two linked videos cover that feature on its own.

Check yourself

  1. 01In `function pipe<T, U>(value: T, fn: (v: T) => U): U`, how does the compiler type `n` in `pipe(5, (n) => n.toFixed(2))`?

    The arrow function's parameter has no annotation, so the arrow is context-sensitive and is held back. In the first pass, `5` gives `T` the candidate `number`. In the next pass the arrow is checked with `T` known, so `n` is `number`, and its return type gives `U` the type `string`.

  2. 02Why does `same(n, s)` fail for `function same<T>(a: T, b: T): T` when `n` is a `number` and `s` is a `string`?

    Both arguments are inference sites for `T`, giving the candidates `number` and `string`. TypeScript picks one candidate that the others fit into rather than unioning them; neither fits the other, so it settles on `number` and reports the `string` argument as not assignable.

  3. 03What is the type of `empty()` for `function empty<T>(): T[]`, and how could the author change it?

    It is `unknown[]`, because there is no inference site and no default, so `T` falls back to `unknown`. A default such as `<T = string>` or a constraint such as `<T extends string>` would change the fallback to that type.

  4. 04Why does `createMachine(["idle", "loading"], "done")` compile when the signature is `createMachine<S extends string>(states: S[], initial: S)`?

    Both parameters are inference sites for `S`, so `"done"` becomes a candidate alongside the two states and `S` is inferred as `"idle" | "loading" | "done"`. The typo widened the type it was supposed to be checked against.

  5. 05How does `NoInfer` fix that `createMachine` signature?

    Changing the second parameter to `initial: NoInfer<S>` removes it as an inference site. `S` is inferred from `states` alone as `"idle" | "loading"`, and then `"done"` is checked against that type and rejected.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark