TypeScript Inference (original) (raw)

Last Updated : 21 Jan, 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,

**More Examples of TypeScript Inference

Inference of Variable 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

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