← Back to TypeScript Course | Chapter 3: Variables and Functions | Lesson 3 of 10

Type Inference

Type inference allows TypeScript to automatically determine a value's type from its initial value. This means you often do not need to write a type annotation explicitly.

Basic Inference

When a variable is initialized with a value, TypeScript can infer its type automatically from that value without needing an explicit annotation. Writing let age = 25 gives age the inferred type number with no extra syntax required.

Example: Basic Inference

typescript
let age = 25; // inferred as number, no annotation needed
console.log(typeof age, age);

Inference with const

Constants also receive an inferred type from whatever value they're assigned, and because const values can never be reassigned, TypeScript can sometimes infer an even more specific literal type than it would for a similarly initialized let.

Example: Inference with const

typescript
const name = "Fixed"; // inferred as the literal type "Fixed", not just string
console.log(name);

Inference in Arrays

TypeScript can infer the element type of an array directly from the values placed inside its initializer, so const nums = [1, 2, 3] is automatically understood as a number[] with no annotation needed. Mixed-type array literals get inferred as a union of those types.

Example: Inference in Arrays

typescript
const nums = [1, 2, 3]; // inferred as number[]
console.log(nums);

Inference in Expressions

Types are also inferred from the result of expressions and operations, such as the return type of a function being inferred from whatever its return statement actually produces. This lets you skip annotating return types on simple functions while TypeScript still keeps them fully checked.

Example: Inference in Expressions

typescript
function add(a: number, b: number) {
  return a + b; // return type inferred as number
}
console.log(add(2, 3));

Inference and Explicit Types

Type inference reduces the need for unnecessary explicit annotations, keeping code less cluttered, while explicit annotations remain useful when you want to clearly document an intended type or deliberately restrict a variable to a narrower type than TypeScript would otherwise infer.

Example: Inference and Explicit Types

typescript
let count = 5; // inferred, no clutter
let id: number = 5; // explicit, documents intent
console.log(count, id);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.