Type Inference

TypeScript can figure out types automatically from the value you assign.

Syntaxlet city = "Paris"; // inferred as string

Type inference means TypeScript guesses the type for you based on the assigned value. You don't need to write the annotation when it is obvious.

Example

Writing let city = "Paris" is enough — TypeScript infers string. Trying to later assign a number would be an error.

Explicit annotations are still useful for function parameters and for documenting intent, but inference keeps everyday code clean.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A developer omits type annotations on simple variable initializations, relying on inference to keep the code clean.
  • A team uses inference for function return types so the compiler automatically validates them against the implementation.
  • A refactor renames a function's return value and relies on inference to update downstream type checks automatically.

More examples

Inferred primitive types

Demonstrates that TypeScript infers the type from the initial value and enforces it on subsequent assignments.

Example · ts
let count = 42;       // inferred: number
let label = 'hello';  // inferred: string
let active = true;    // inferred: boolean

count = 'oops';       // Error: Type 'string' is not assignable to type 'number'

Inferred function return type

Shows that TypeScript infers the return type from the return statement without requiring an explicit annotation.

Example · ts
function multiply(a: number, b: number) {
  return a * b; // return type inferred as number
}

const result = multiply(3, 4); // result inferred as number

Inference in array literals

Illustrates how TypeScript infers array element types from the initial literal, including union types for mixed arrays.

Example · ts
const fruits = ['apple', 'banana', 'cherry']; // string[]
const mixed = [1, 'two', true];               // (number | string | boolean)[]

fruits.push(42); // Error: Argument of type 'number' is not assignable

Discussion

  • Be the first to comment on this lesson.