Skip to content

Type Inference

In one line

Type inference is TypeScript's ability to automatically figure out the type of a variable or expression from its usage, without requiring an explicit annotation.

In simple words

Type inference means TypeScript guesses the type for you. When you write let x = 5, TypeScript infers that x is a number — you don't need to write let x: number = 5. This keeps code concise while maintaining type safety.

Inference works for variables, return types, and generic type parameters. For example, if you call identity(42) where identity is <T>(x: T) => T, TypeScript infers that T is number.

There are limits: TypeScript cannot infer function parameter types (you must annotate them), and inference may widen literal types. For let x = 5, x is inferred as number (widened), but for const x = 5, x is inferred as the literal type 5.

Example

typescript
let count = 5;        // inferred: number
const pi = 3.14;     // inferred: 3.14 (literal)
let names = ["a"];  // inferred: string[]

function double(x) { return x * 2; } // Error: parameter needs annotation

TypeScript infers types from initializers. Function parameters must be annotated explicitly.

Common confusions

  • Confused with: type annotation

    The difference: Inference is automatic; annotation is explicit. Inference keeps code shorter, but annotations are clearer for public APIs.

Related terms

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary