Lesson 9 of 60 – Type Inference
15%

Type Inference in TypeScript

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.

Note: You do not always need to write a type annotation. When TypeScript can determine the type from the value, it can infer the type automatically.

1. What is Type Inference?

Type inference means TypeScript automatically identifies the type of a value.

let name = "Rahul";

TypeScript can infer that name is a string.

2. Type Inference with Numbers

If a number is assigned to a variable, TypeScript can infer the number type.

let age = 20;

TypeScript understands that age is a number.

3. Type Inference with Strings

let city = "Aurangabad";

TypeScript infers the type of city as string.

Therefore, you do not necessarily need to write:

let city: string = "Aurangabad";

4. Type Inference with Boolean

let isStudent = true;

TypeScript can infer that isStudent is a boolean.

5. Type Inference with Arrays

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[]

6. String Array Inference

let students = [
    "Amit",
    "Rahul",
    "Priya"
];

TypeScript can infer that students is a string[].

7. Boolean Array Inference

let results = [
    true,
    false,
    true
];

TypeScript infers this as an array of boolean values.

8. Type Inference vs Type Annotation

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.

9. TypeScript Remembers the Inferred Type

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.

10. Inference Happens from the Initial Value

TypeScript commonly uses the initial value to determine a variable's type.

let price = 500;

The compiler can infer:

price: number

11. Inference with const

Type inference also works with const.

const country = "India";

TypeScript knows that country contains a string value.

12. Inference in Expressions

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.

13. Inference with String Concatenation

let firstName = "Rahul";
let lastName = "Kumar";

let fullName = firstName + " " + lastName;

TypeScript infers fullName as a string.

14. Inference in Functions

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.

15. Inferred Function Return Type

function getMessage() {
    return "Hello TypeScript";
}

TypeScript can infer that this function returns a string.

You could explicitly write:

function getMessage(): string {
    return "Hello TypeScript";
}

16. Inference in Arrow Functions

TypeScript also performs inference with arrow functions.

const add = (a: number, b: number) => {
    return a + b;
};

The return type can be inferred as number.

17. Inference with Object Properties

let student = {
    name: "Amit",
    age: 20
};

TypeScript can infer:

  • name as string
  • age as number

18. Accessing Inferred Object Properties

let student = {
    name: "Amit",
    age: 20
};

console.log(student.name);
console.log(student.age);

TypeScript knows that the object contains name and age properties.

19. Inference with Nested Objects

let student = {
    name: "Rahul",
    address: {
        city: "Patna",
        pin: 800001
    }
};

TypeScript can infer the types of the nested properties as well.

20. Inference with Conditional Expressions

let age = 20;

let status = age >= 18
    ? "Adult"
    : "Minor";

TypeScript can infer status as a string because both possible results are strings.

21. Inference with Function Parameters

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.

22. Contextual Typing

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.

23. Inference with Map()

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.

24. Inference Can Reduce Repeated Code

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.

25. When Explicit Types Are Useful

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.

26. Type Inference in React Native

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.

27. Inference with React Native Data

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.

28. Type Inference Example

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 string
  • age as number
  • marks as number array
  • calculateTotal() as returning number
  • total as number

29. Type Annotation vs Inference

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

30. Important Rules of Type Inference

Remember these important points:

  1. TypeScript can determine types from assigned values.
  2. Strings are inferred as strings.
  3. Numbers are inferred as numbers.
  4. Boolean values are inferred as booleans.
  5. Array element types can be inferred.
  6. Object property types can be inferred.
  7. Function return types can often be inferred.
  8. Context can help TypeScript infer types.
  9. Explicit annotations are still useful when you need to describe intent.
  10. Type inference is especially useful for writing cleaner TypeScript code.
Remember: Type inference allows TypeScript to understand many types automatically. You do not need to add a type annotation everywhere.

📌 Key Points

  • Type inference means TypeScript automatically determines a type.
  • TypeScript can infer types from initial values.
  • Strings, numbers, and booleans can be inferred.
  • Array and object types can also be inferred.
  • Function return types can often be inferred.
  • Contextual typing helps TypeScript determine types in certain situations.
  • Type inference can reduce unnecessary type annotations.
  • Explicit annotations are useful when you need to clearly define a type.
  • Type inference works naturally with React and React Native code.
  • Understanding inference helps you write cleaner TypeScript programs.

🧠 Quick Quiz

Question: What does TypeScript do when it can determine a variable's type automatically?