Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Concepts and Comparisons

Type inference in TypeScript

How TypeScript infers types from initializers, return values, contexts and generics, when annotations help, and where inference gives up.

Type inference is the compiler working out a type you did not write. When you write const n = 5, TypeScript knows n is the literal 5; when you write let s = "hi", it knows s is a string. You get the safety of types with far fewer annotations.

Inference happens in a few distinct places: from initial values, from the body of a function (its return type), from the context where an expression is used (contextual typing), and from the arguments passed to a generic function.

TypeScript
let total = 0;               // number
const names = ["a", "b"];    // string[]
const first = names[0];      // string

Try it

TypeScript Inference from values and returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Contextual typing and generics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The main kinds of inference

From initializers

A variable's type comes from its initial value. let widens literals to their base type; const keeps the literal. See Widening and narrowing.

From return statements

A function without a return annotation gets the union of all returned expression types. Exported APIs usually benefit from an explicit annotation so a change inside the body cannot silently change the public type.

Contextual typing

When an expression is placed where a type is already expected, such as a callback argument or an object assigned to an annotated variable, its parts take their types from that expectation.

Generic inference

TypeScript collects candidates for each type parameter from the arguments and picks the best common type. Candidates in a contravariant position (parameters) are intersected rather than unioned.

Usage notes

  • Annotate boundaries, infer interiors. Parameters and exported return types deserve annotations; local variables rarely do.
  • Empty collections infer poorly. const xs = [] is evolving any[] under noImplicitAny; annotate it as number[].
  • satisfies checks a value against a type while keeping the inferred type; see satisfies.
  • as const asks for the narrowest inference; see as const.
  • Inference never invents any silently with noImplicitAny on; it reports TS7006 or TS7034 instead.
  • Generic defaults and NoInfer control which arguments may contribute candidates; see NoInfer.