Type Inference in TypeScript

TypeScript infers types based on the assigned value, reducing the need for explicit type annotations.

đź§  Main idea:

Type Inference means that TypeScript automatically figures out the type of a variable based on the assigned value, so you don’t always have to manually annotate types.

Simple Example:

typescript
1let name = "Alice";

TypeScript infers that name is a string, even though you didn’t explicitly write : string.

If you later try to assign a number:

typescript
1name = 123; // ❌ Error: Type 'number' is not assignable to type 'string'.

TypeScript will prevent it!

Where Type Inference Happens:

  • Variables
typescript
1let count = 42; // inferred as number
  • Function Return Types:
typescript
1function getGreeting() { 2 return "Hello!"; 3}

Inferred return type: string

  • Function Parameters (with Contextual Typing):
typescript
1const numbers = [1, 2, 3]; 2numbers.forEach(num => { 3 console.log(num.toFixed(2)); // num is inferred as number 4});

Here, num is automatically inferred as number because numbers is an array of numbers.

  • Destructuring:
typescript
1const user = { name: "Alice", age: 30 }; 2 3const { name, age } = user; 4// name: string 5// age: number

Why is it useful?

  • Less code — no need to annotate every variable manually.
  • Safer code — still gets all the type-checking benefits.