TypeScript Inference
Last Updated : 21 Jan, 2025
Improve
TypeScript's type inference automatically determines the types of variables, function return values, objects, and arrays based on their assigned values and usage.
- This feature reduces the need for explicit type annotations, simplifying code while maintaining type safety.
- By analyzing the context and initial values, TypeScript ensures that variables and functions operate with consistent and expected types throughout the codebase.
let age = 25;
let name = "John";
console.log(`Age: ${age}`);
console.log(`Name: ${name}`);
In this Example,
- TypeScript infers age as a number and name as a string based on their assigned values.
- This automatic detection ensures type safety without requiring explicit annotations.
More Examples of TypeScript Inference
Inference of Variable Type
let x = 10; // TypeScript infers x as a number
console.log(typeof x);
In this Example,
- TypeScript infers the type of x as number based on the initial value 10.
- This ensures x can only hold numerical values, improving type safety.
Output:
number
Inference of Array Type
let fruits = ["Apple", "Banana", "Cherry"]; // TypeScript infers fruits as string[]
console.log(fruits);
In this Example,
- TypeScript infers the type of fruits as an array of strings (string[]) based on the initial values.
- This prevents adding elements of other types, maintaining array consistency.
Output:
[ 'Apple', 'Banana', 'Cherry' ]
Inference of Function Return Type
function add(a: number, b: number) {
return a + b; // TypeScript infers the return type as number
}
console.log(add(5, 10));
In this Example,
- The add function's return type is inferred as number because it returns the sum of two numbers.
- This ensures the function always returns a numerical value, avoiding type-related errors.
Output:
15