TypeScript Inference
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
TypeScript Inference - FAQs
What is type inference in TypeScript?
Type inference is the process by which TypeScript automatically determines the type of a variable, function, or expression based on its value or context.
When does TypeScript infer types?
TypeScript infers types during variable declarations, function return values, and parameter default values.
Can I override TypeScript's inferred types?
Yes, you can explicitly annotate types if the inferred type doesn’t match your intention.
How does TypeScript infer types for arrays?
TypeScript infers the type of an array based on its initial elements, creating a consistent type for all elements.
Is type inference always accurate?
In most cases, yes. However, in complex scenarios or mixed data types, it may infer broader types like any or unions, which might need manual adjustments.