Type inference is a feature of TypeScript that allows the compiler to automatically determine the type of a variable based on the value assigned to it.
Type inference means TypeScript automatically identifies the type of a value.
let name = "Rahul";
TypeScript can infer that name is a string.
If a number is assigned to a variable, TypeScript can infer the
number type.
let age = 20;
TypeScript understands that age is a number.
let city = "Aurangabad";
TypeScript infers the type of city as
string.
Therefore, you do not necessarily need to write:
let city: string = "Aurangabad";
let isStudent = true;
TypeScript can infer that isStudent is a boolean.
TypeScript can also infer the type of an array from its elements.
let marks = [80, 90, 75, 88];
TypeScript infers this as an array of numbers.
number[]
let students = [
"Amit",
"Rahul",
"Priya"
];
TypeScript can infer that students is a
string[].
let results = [
true,
false,
true
];
TypeScript infers this as an array of boolean values.
With type annotation:
let age: number = 20;
With type inference:
let age = 20;
In the second example, TypeScript automatically determines that
age is a number.
let age = 20;
age = 25;
The assignment is valid because both values are numbers.
But this is not compatible:
age = "Twenty";
TypeScript can report a type error because age was inferred
as a number.
TypeScript commonly uses the initial value to determine a variable's type.
let price = 500;
The compiler can infer:
price: number
Type inference also works with const.
const country = "India";
TypeScript knows that country contains a string value.
TypeScript can infer the result of expressions.
let a = 10;
let b = 20;
let total = a + b;
Because a and b are numbers,
TypeScript infers total as a number.
let firstName = "Rahul";
let lastName = "Kumar";
let fullName = firstName + " " + lastName;
TypeScript infers fullName as a string.
TypeScript can often infer the return type of a function.
function add(a: number, b: number) {
return a + b;
}
The return value is a number, so TypeScript can infer the function's
return type as number.
function getMessage() {
return "Hello TypeScript";
}
TypeScript can infer that this function returns a string.
You could explicitly write:
function getMessage(): string {
return "Hello TypeScript";
}
TypeScript also performs inference with arrow functions.
const add = (a: number, b: number) => {
return a + b;
};
The return type can be inferred as number.
let student = {
name: "Amit",
age: 20
};
TypeScript can infer:
name as stringage as numberlet student = {
name: "Amit",
age: 20
};
console.log(student.name);
console.log(student.age);
TypeScript knows that the object contains name and
age properties.
let student = {
name: "Rahul",
address: {
city: "Patna",
pin: 800001
}
};
TypeScript can infer the types of the nested properties as well.
let age = 20;
let status = age >= 18
? "Adult"
: "Minor";
TypeScript can infer status as a string because both
possible results are strings.
Function parameters usually need types when they cannot be inferred from the surrounding context.
function greet(name: string) {
return "Hello " + name;
}
Here the parameter type is explicitly provided.
Sometimes TypeScript can infer a type from the context in which a value is used. This is called contextual typing.
const numbers: number[] = [10, 20, 30];
numbers.forEach((number) => {
console.log(number);
});
The callback parameter number can be understood as a number
because the array is a number array.
let numbers = [1, 2, 3, 4];
let doubled = numbers.map((number) => {
return number * 2;
});
TypeScript can infer that number is a number and that
doubled is a number array.
Without inference, you might need to write many type annotations.
let name: string = "Amit";
let age: number = 20;
let active: boolean = true;
With inference:
let name = "Amit";
let age = 20;
let active = true;
TypeScript can determine the types automatically in these examples.
Although inference is useful, explicit type annotations can make intent clearer or describe a type that cannot be determined from an initial value.
let studentName: string;
studentName = "Rahul";
The type is explicitly declared before a value is assigned.
Type inference is very useful when developing React Native applications. For example:
const userName = "Rahul";
const userAge = 21;
const isLoggedIn = true;
TypeScript can infer the types of these values without requiring explicit annotations.
const user = {
id: 101,
name: "Rahul",
active: true
};
TypeScript can infer the structure and types of the object. This can make everyday application code shorter while maintaining type information.
let studentName = "Amit";
let age = 20;
let marks = [80, 90, 85];
function calculateTotal() {
return marks[0] + marks[1] + marks[2];
}
let total = calculateTotal();
console.log(studentName);
console.log(age);
console.log(marks);
console.log(total);
TypeScript can infer:
studentName as stringage as numbermarks as number arraycalculateTotal() as returning numbertotal as number| Feature | Type Annotation | Type Inference |
|---|---|---|
| Type specified manually | Yes | No |
| Compiler determines type | Sometimes checks it | Yes |
| Example | let age: number = 20; |
let age = 20; |
| Code length | Can be longer | Often shorter |
| Useful for | Explicit contracts | Automatically determined types |
Remember these important points:
Question: What does TypeScript do when it can determine a variable's type automatically?