How Inference Works

Not started · 0% · difficulty 2/5

✎ Edit knowledge

Letting the compiler deduce types from initializers.

Topics

1. Practice

practice · 7 tasks

Practice

Practice · 1 / 6

In `let count = 42;`, what type does TypeScript infer for `count`?

Knowledge

How Type Inference Works

When you declare a variable with an initializer but no type annotation, TypeScript automatically deduces (infers) the variable's type from the value on the right-hand side. This means you rarely need to annotate everything by hand.

let count = 42;       // inferred as: number
let name = "Ada";      // inferred as: string
let active = true;    // inferred as: boolean
let nums = [1, 2, 3]; // inferred as: number[]

Best common type

For arrays and other collections, TypeScript computes a 'best common type' from all the elements. If the elements have different types, the result is a union of those types.

let mixed = [1, "two", 3]; // inferred as: (string | number)[]
let flags = [true, false]; // inferred as: boolean[]

Return type inference

Function return types are inferred from the return statements in the body, so you usually only need to annotate the parameters.

function add(a: number, b: number) {
  return a + b; // return type inferred as: number
}

When inference gives up

A declaration with neither an initializer nor an annotation falls back to the any type. Under the recommended noImplicitAny option this is a compile error, so annotate those cases explicitly.

  • Inference reads the initializer's value to choose a type

  • Arrays get the best common type of their elements

  • Function return types come from the return statements

  • No initializer and no annotation => any (an error under noImplicitAny)