Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Type Inference

Learn how TypeScript automatically determines variable types from values, function return types, and context with practical examples and expected outputs.

Simple Explanation: Type inference is a feature in which TypeScript determines a value's type automatically when enough information is available. You do not always need to write type annotations manually.

What Will We Learn?

Type inference makes TypeScript code easier to read and write while retaining useful type checking.

  • Understand automatic type inference.
  • Infer types from variable initialization.
  • Understand inferred function return types.
  • Learn contextual typing.
  • Identify when explicit type annotations are useful.

Type Inference Workflow

Follow these steps to understand how TypeScript identifies types without requiring annotations everywhere.

📝
Step 1
Write Code

Assign a value.

→
🧠
Step 2
Infer Type

TypeScript analyzes the value.

→
✅
Step 3
Type Checking

Check compatible operations.

→
🚀
Step 4
Compile

Generate JavaScript.

1. What Is Type Inference?

Type inference allows TypeScript to determine the type of a variable from its initial value.

Example

let studentName = "Rahul";
let age = 22;
let isEnrolled = true;

console.log(studentName);
console.log(age);
console.log(isEnrolled);

Expected Output

Rahul
22
true

Inferred Types

Variable Initial Value Inferred Type
studentName "Rahul" string
age 22 number
isEnrolled true boolean

The variable declarations do not contain explicit type annotations, but TypeScript can still determine their types.

2. Type Inference with String

When a variable is initialized with a string value, TypeScript normally infers the variable type as string.

Example

let courseName = "TypeScript";
let instituteName = "CIIT Training Institute";

console.log(courseName.toUpperCase());
console.log(instituteName);

Expected Output

TYPESCRIPT
CIIT Training Institute

TypeScript knows that courseName is a string, so string methods such as toUpperCase() are available.

3. Type Inference with Numbers

When a variable is initialized with a numeric value, TypeScript normally infers the type as number.

Example

let courseFees = 35000;
let discount = 5000;

let finalFees = courseFees - discount;

console.log("Course Fees: " + courseFees);
console.log("Discount: " + discount);
console.log("Final Fees: " + finalFees);

Expected Output

Course Fees: 35000
Discount: 5000
Final Fees: 30000

TypeScript infers the types of the numeric variables without requiring : number on each declaration.

4. Type Inference with Arrays

TypeScript can infer the element type of an array from its initial elements.

Example

let marks = [75, 85, 90];
let students = ["Rahul", "Priya", "Amit"];

marks.push(95);
students.push("Sneha");

console.log(marks);
console.log(students);

Expected Output

[ 75, 85, 90, 95 ]
[ 'Rahul', 'Priya', 'Amit', 'Sneha' ]

In this example, TypeScript infers an array of numbers for marks and an array of strings for students. The displayed formatting can vary by JavaScript runtime.

5. Function Return Type Inference

TypeScript can infer the return type of a function by examining its return statements.

Example

function addNumbers(a: number, b: number) {
    return a + b;
}

let result = addNumbers(10, 20);

console.log(result);

Expected Output

30

Inferred Types

  • Parameter a: number
  • Parameter b: number
  • Function return type: number

In this example, the parameters are explicitly typed, while the return type is inferred as number.

6. Contextual Typing

Contextual typing occurs when TypeScript infers a type from the surrounding context, such as an expected callback signature.

Example

const studentNames: string[] = ["Rahul", "Priya", "Amit"];

studentNames.forEach(name => {
    console.log(name.toUpperCase());
});

Expected Output

RAHUL
PRIYA
AMIT

Since studentNames is a string array, TypeScript can infer that the callback parameter name is a string.

7. Type Inference vs Explicit Types

TypeScript supports both inferred types and explicit type annotations. Choose the approach that makes your code clear and easy to maintain.

Example

// Type inference
let studentName = "Rahul";
let age = 22;

// Explicit type annotations
let courseName: string = "TypeScript";
let fees: number = 35000;

console.log(studentName);
console.log(age);
console.log(courseName);
console.log(fees);

Expected Output

Rahul
22
TypeScript
35000
Approach Example Explanation
Type inference let age = 22; TypeScript infers the type as number.
Explicit type let age: number = 22; The developer specifies the type.
Best Practice: Use type inference when the type is obvious. Add explicit annotations when they improve readability or define a clear contract.

8. Type Inference and Reassignment

When TypeScript infers a variable as a string or number, it checks later assignments against the inferred type.

Example

let courseName = "TypeScript";

courseName = "JavaScript";

console.log(courseName);

// This assignment would produce a type error:
// courseName = 100;

Expected Output

JavaScript

TypeScript infers courseName as a string. Reassigning another string is allowed, but assigning a number is not compatible with the inferred type.

9. When Should You Write Explicit Types?

Type inference is useful, but explicit annotations can make code clearer when the expected type is not obvious.

Example

let selectedCourse: string | null = null;

selectedCourse = "Dot Net Full Stack";

console.log(selectedCourse);

Expected Output

Dot Net Full Stack

The explicit union type allows selectedCourse to contain either a string or null.

Common Mistakes

  • Assuming that a variable inferred as a string can later accept any type of value.
  • Confusing type inference with runtime type checking.
  • Assuming TypeScript requires explicit annotations on every variable.
  • Forgetting that contextual typing can infer callback parameter types.
  • Using type annotations that do not match the intended values.
Remember: Type inference happens during TypeScript analysis and compilation. Type annotations are not generally present in the generated JavaScript.

Practical Example: CIIT Course Registration

Let's use type inference in a course registration example for CIIT Training Institute.

Example

const instituteName = "CIIT Training Institute";

let studentName = "Priya";
let courseName = "Dot Net Full Stack";
let fees = 35000;
let isRegistered = true;

function getDiscount(amount: number) {
    return amount - 5000;
}

let finalFees = getDiscount(fees);

console.log("Institute: " + instituteName);
console.log("Student: " + studentName);
console.log("Course: " + courseName);
console.log("Original Fees: " + fees);
console.log("Final Fees: " + finalFees);
console.log("Registered: " + isRegistered);

Expected Output

Institute: CIIT Training Institute
Student: Priya
Course: Dot Net Full Stack
Original Fees: 35000
Final Fees: 30000
Registered: true

TypeScript infers the types of the initialized variables, the function's numeric return type, and the value assigned to finalFees.

Practice Task

Create a TypeScript program for employee information using type inference wherever appropriate.

  • Employee name: Amit
  • Employee ID: 101
  • Salary: 45000
  • Is active: true
  • Calculate annual salary using a function.

Hint

let employeeName = "Amit";
let employeeId = 101;
let salary = 45000;
let isActive = true;

function calculateAnnualSalary(monthlySalary: number) {
    return monthlySalary * 12;
}

let annualSalary = calculateAnnualSalary(salary);

console.log(employeeName);
console.log(employeeId);
console.log(salary);
console.log(isActive);
console.log(annualSalary);

Expected Output

Amit
101
45000
true
540000

Summary

In this lesson, we learned how TypeScript infers types from initialized variables, arrays, function return statements, and surrounding context.

Key Point: Type inference reduces repetitive annotations while preserving TypeScript's type checking. Use explicit annotations when they make the intended type clearer.