Learn/TypeScript/2. Values and types
Lesson 2 of 15
Sign in

TypeScript, lesson 2

Values and types

A variable is a name for a value. TypeScript adds one more thing to every variable: a type, which describes what values the variable may hold. The type checker uses it to catch mistakes, and your editor uses it to suggest methods and show documentation.

const, let and annotations

Prefer const; use let only when you will reassign. (Avoid the old var keyword.) The annotation goes after the name, separated by a colon. Assigning a value of the wrong type is a type error:

Type inference

You rarely need to write annotations on variables, because TypeScript infers the type from the starting value:

The idiom is to let inference work for local variables and to annotate function parameters (you will see why in the functions lesson). Hover over a variable in the editor to see what TypeScript inferred.

2 exercises to try what you just read.

Exercise 1

Planet facts

Press Ctrl Enter or Check to test your code.

Exercise 2

Traffic light

Press Ctrl Enter or Check to test your code.

The basic types

TypeExample values
number42, -0.5, 1e9 (whole and decimal numbers share one type)
string"hi", 'ok', `x`
booleantrue, false
bigint10n (whole numbers of any size)
null, undefined"no value"

Write these in lower case. String and Number with capitals refer to wrapper objects you almost never want. There is also any, which switches type checking off for a value. It is an escape hatch; avoid it.

Literal types and as const

A type can also be one exact value. Combined with | ("or"), this describes a small set of allowed values:

const variables get literal types automatically: const size = "large" has the type "large", because it can never change. Writing as const after an array or object makes all of its contents read-only literal values too.

Template literals

Backtick strings can embed any expression with ${ }:

Types disappear at run time

TypeScript's types exist only while you edit and check the code. When the program runs, they are gone, so a type cannot change how a value behaves. typeof is a JavaScript operator that inspects a real value at run time:

Numbers are 64-bit floating point, so 0.1 + 0.2 prints 0.30000000000000004. Round when you display decimals (with toFixed, coming next lesson).

Further reading

  • TypeScript Handbook: Everyday Types
  • TypeScript Handbook: Literal types
  • MDN: Grammar and types

Declare these variables with explicit type annotations: name (string) Jupiter, moons (number) 95, hasRings (boolean) true, and dayHours (number) 9.9. Then print exactly:

Compute the last value from dayHours instead of typing 99. (Hint: Math.round avoids a floating-point surprise.) The program reads no input.

A traffic light can only be "red", "amber" or "green". Declare a type alias for that set of values:

Then declare let light: Light = "red"; and print it. Change it to "green" and print it, then to "amber" and print it, then back to "red" and print it. Finally print the result of typeof light.

Expected output:

const city: string = "Lagos";   // never reassigned
let lives: number = 3;          // will change
lives = lives - 1;
let lives: number = 3;
lives = "three";   // error: Type 'string' is not assignable to type 'number'.
let score = 0;          // inferred: number
const name = "Kai";     // inferred: the literal type "Kai"
let direction: "left" | "right" = "left";
direction = "right";   // fine
direction = "up";      // error: not one of the allowed values
const item = "lamp";
const price = 24.5;
console.log(`A ${item} costs ${price} EUR, two cost ${price * 2} EUR.`);
console.log(typeof 3, typeof "3", typeof true);   // number string boolean
Jupiter has 95 moons.
Rings: true
A day lasts 9.9 hours.
Ten days last 99 hours.
type Light = "red" | "amber" | "green";
red
green
amber
red
string