TypeScript Inference

Last Updated : 19 Aug, 2026

Type inference allows TypeScript to automatically determine the type of variables, function return values, objects, and arrays based on their assigned values, reducing the need for explicit type annotations.

Typescript
  • Automatically infers types from assigned values.
  • Reduces the need for explicit type annotations.
  • Improves type safety and code readability.
  • Provides better IDE support with autocompletion and error checking.
JavaScript
let age = 25;
let name = "John";

console.log(`Age: ${age}`);
console.log(`Name: ${name}`);
  • age is inferred as number.
  • name is inferred as string.
  • No explicit type annotations are required.

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);
  • x is inferred as number.
  • Only numeric values can be assigned to x.

Output:

number

Inference of Array Type

Array type inference allows TypeScript to automatically determine the type of an array based on the elements it contains.

JavaScript
let fruits = ["Apple", "Banana", "Cherry"]; // TypeScript infers fruits as string[]
console.log(fruits);
  • fruits is inferred as string[].
  • The array accepts only string values.

Output:

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

Inference of Function Return Type

Function return type inference means the compiler or interpreter automatically determines the return type of a function based on the value it returns. Instead of explicitly specifying the return type, the language infers it from the returned value.

JavaScript
function add(a: number, b: number) {
    return a + b; // TypeScript infers the return type as number
}
console.log(add(5, 10));
  • The add function's return type is inferred as number because it returns the sum of two numbers.
  • This helps maintain type consistency and prevents type-related errors.

Output:

15

Inference of Object Type

Array type inference allows TypeScript to automatically determine the type of an array based on the elements it contains.

JavaScript
let person = {
    name: "Alen",
    age: 30
};

console.log(person);

Output:

{ name: 'Alen', age: 30 }
  • person is inferred as an object with name and age properties.
  • TypeScript automatically determines the type of each property.
Comment

Explore