Course outline · 0% complete

0/26 lessons0%

Course overview →

Annotating Variables

lesson 1-2 · ~10 min · 2/26

The annotation syntax

An annotation exists because a variable's type is a promise to every line that reads it later. In a real file, city might be used fifty lines below its declaration — if anything in between reassigns it to a number, every one of those reads becomes a latent crash. Writing the type down turns the promise into something the compiler enforces.

A type annotation goes after the variable name, separated by a colon:

let city: string = "Tokyo";
let population: number = 37000000;
let isCapital: boolean = true;

Compare with the JavaScript you wrote before:

let city = "Tokyo"; // could be reassigned to anything

In TypeScript, city is now locked to strings. Try city = 42 later in the file and the compiler answers: Type 'number' is not assignable to type 'string'. The three primitive types you will use constantly are string, number, and boolean. Note they are lowercase, matching what JavaScript's typeof operator returns.

Code exercise · typescript

Run this, then add a line that reassigns city to a number (city = 5) and run again. The compiler should stop you.

Inference: TypeScript often knows already

Write let city = "Tokyo" with no annotation and hover it in an editor: TypeScript reports the type is string anyway. This is type inference, the compiler deducing a type from the value you assigned. The rules real codebases follow:

  • If the variable is initialized on the same line, let inference work, do not repeat yourself
  • Annotate when there is no initializer, or when the inferred type is not what you intend

So let count = 0 needs no annotation, but let count: number (declared now, assigned later) does. Inference is why idiomatic TypeScript often looks nearly identical to JavaScript.

const infers more precisely than let

Inference also reacts to how the variable is declared. let city = "Tokyo" is inferred as string, because a let may be reassigned to any other string later. const city = "Tokyo" is inferred as the exact type "Tokyo" — a type whose only allowed value is that one string — because a const can never change, so the compiler keeps every bit of information it has.

let a = "Tokyo";   // type: string
const b = "Tokyo"; // type: "Tokyo"

You will rarely notice the difference day to day, but it explains editor tooltips, and lesson 2-3 turns these exact-value types (literal types) into a genuinely useful tool.

Quiz

What is the inferred type of score in: let score = 10

Code exercise · typescript

Your turn. Declare three variables about a movie with explicit annotations: movie (string) set to "Arrival", year (number) set to 2016, and rewatchable (boolean) set to true. Then print them with the exact format shown in the expected output.