ReviseAlgo Logo

TypeScript Fundamentals

Type Inference

Understand how the TypeScript compiler automatically infers types without explicit annotations, Best Common Type algorithm, contextual typing, and when annotations are required.

Last Updated: July 29, 2026 10 min read

TypeScript is smart enough to infer types automatically when you do not provide explicit type annotations. Type Inference allows developers to write clean code without cluttering every single variable with explicit types, while retaining full static type safety.

1. How Type Inference Works

When a variable is initialized with a value, TypeScript inspects the assignment and assigns a type automatically:

2. Types of Inference

1. Simple Initialization Inference

2. Best Common Type Algorithm

When inferring types from an array or multiple expressions, TypeScript calculates the Best Common Type by evaluating all item types.

3. Contextual Typing

TypeScript infers types based on the location or context in which an expression occurs (such as event handlers or callbacks).

3. Inferring Function Return Types

TypeScript automatically infers function return types by analyzing return statements:

4. When to Use Annotations vs Inference

Rule of Thumb

  • Let TypeScript infer: Local variables with immediate initialization (let x = 10;, const name = "Alice";).
  • Use explicit annotations: Function parameters, public API signatures, complex object returns, and uninitialized variables.
  • 5. Interactive Code Playground

    Experiment with inference behavior below:

    6. Common Pitfalls & Edge Cases

  • const vs let Type Widening:
  • - let x = "hello" is inferred as string (can be reassigned to any string). - const y = "hello" is inferred as the narrow literal type "hello" (cannot be changed).
  • Uninitialized Variables:
  • Declaring let data; without an initial value infers any. Subsequent assignments will not restrict its type later unless annotated.

    7. Summary Comparison Table

    ScenarioInference ResultBest Practice
    const x = 5Literal type 5Rely on inference
    let x = 5numberRely on inference
    Function parametersany (without strict mode)Always annotate explicitly
    Function return typesInferred from return statementsAnnotate for public APIs
    | Uninitialized let x | any | Always annotate explicitly |