TypeScript Inference (original) (raw)

Last Updated : 9 Sep, 2025

TypeScript's type inference automatically determines the types of variables, function return values, objects, and arrays based on their assigned values and usage.

let age = 25; let name = "John";

console.log(Age: ${age}); console.log(Name: ${name});

``

**In this Example

Inference of Variable Type

Variable type inference means the programming language automatically deduces the type of a variable from the value assigned to it, without the programmer explicitly specifying the type.

JavaScript `

let x = 10; // TypeScript infers x as a number console.log(typeof x);

`

**In this Example,

**Output:

number

**Inference of Array Type

JavaScript `

let fruits = ["Apple", "Banana", "Cherry"]; // TypeScript infers fruits as string[] console.log(fruits);

`

**In this Example,

**Output:

[ 'Apple', 'Banana', 'Cherry' ]

**Inference of Function Return Type

Array type inference means the compiler or interpreter automatically determines the type of an array based on the elements it contains. Instead of explicitly declaring the array’s type, the language infers it from the assigned values.

JavaScript `

function add(a: number, b: number) { return a + b; // TypeScript infers the return type as number } console.log(add(5, 10));

`

**In this Example,

**Output:

15