0
0
Typescriptprogramming~5 mins

How TypeScript infers types automatically

Choose your learning style9 modes available
Introduction

TypeScript guesses the type of a value without you telling it. This helps catch mistakes early and makes coding easier.

When you declare a variable and assign a value right away.
When you write a function and return a value without specifying the return type.
When you create an array or object with initial values.
When you want TypeScript to help you by understanding your code automatically.
Syntax
Typescript
let variable = value;

function example() {
  return value;
}

TypeScript looks at the value on the right side to decide the type.

You don't have to write the type explicitly if TypeScript can figure it out.

Examples
TypeScript knows age is a number because 25 is a number.
Typescript
let age = 25;
TypeScript infers name as a string from the text "Alice".
Typescript
let name = "Alice";
The function greet returns a string, so TypeScript infers its return type as string.
Typescript
function greet() {
  return "Hello!";
}
TypeScript infers numbers as an array of numbers (number[]).
Typescript
const numbers = [1, 2, 3];
Sample Program

This program shows TypeScript guessing types for variables and function return values. count is a number, so double knows x is a number and returns a number.

Typescript
let count = 10;
let message = "You have " + count + " new messages.";

function double(x: number) {
  return x * 2;
}

const result = double(count);

console.log(message);
console.log(result);
OutputSuccess
Important Notes

If you don't assign a value when declaring a variable, TypeScript will give it the type any, which means it can be anything.

You can still add explicit types if you want to be clear or catch errors sooner.

Summary

TypeScript automatically guesses types from the values you assign.

This helps find mistakes and makes your code safer without extra work.

You can mix inferred types with explicit types as needed.