Swipe
SwipeSwipe
Swipe Apps

Paths

Motivation

Information

Basic Types · Lesson 5 of 12

Type Inference

A free lesson from Swipe Coding · TypeScript, level 2 · updated October 2026

By the Swipe team, founded by Colin · how we make lessons

🤖
TypeScript is quietly smart about this — you often don't have to tell it anything at all. 🧠

You don't have to annotate every single variable. If you give a variable an initial value, TypeScript looks at that value and infers its type automatically — you get the same safety without typing it out yourself.

let city = "Lagos"; // inferred as string, no annotation needed
city = 42; // Error: Type 'number' is not assignable to type 'string'.
TypeScript never saw an explicit : string, but it inferred one from "Lagos" the moment the variable was declared — and it still enforces that type afterward.

This is why so much everyday TypeScript code looks just like plain JavaScript: as long as a variable is declared with an initial value, an explicit annotation would just be repeating information TypeScript already figured out on its own.

let score = 100;      // inferred: number
let isDone = false;   // inferred: boolean
let label = "total";  // inferred: string
None of these need annotations — the initial value already tells TypeScript everything it needs to know.
🤖
This is the flip side of inference — no initial value means no free lunch. 🍽️

Inference stops working once there's no initial value to look at. Declare a variable without assigning it right away, and TypeScript can't guess what it's for — that's exactly when an explicit annotation earns its keep.

let total;          // no initial value — inferred as 'any', losing type safety
let total2: number; // explicit annotation — TypeScript still enforces it once assigned

total2 = "oops"; // Error: Type 'string' is not assignable to type 'number'.
Without an annotation, total falls back to any and loses type checking entirely. total2 keeps its promise even though it wasn't assigned a value up front.
Fill in the blank

When a variable is declared with an initial value, TypeScript automatically ____ its type — no annotation required.

Quick check

In which situation do you need an explicit type annotation instead of relying on inference?

True or false

let count = 5; requires an explicit : number annotation for TypeScript to treat count as a number.

Keep your streak going in Swipe Coding

Swipe through every level of TypeScript on your iPhone — with XP, stars, streaks, a personal advisor and the full track beyond these free levels.

Get the Swipe apps →