Adding types in TypeScript
Topic 2 of 37 · 9 minFree lessonEvery value in JavaScript has a type, whether you write it down or not. In TypeScript you can write it down. Then TypeScript holds you to it: a variable meant for text can't end up holding a number by mistake.
The three basic types
Most values you've used so far are one of three types:
string: text, like"Lisbon"or'hello'number: any number, whole or decimal, like42or3.5boolean:trueorfalse
To give a variable a type, write a colon and the type after its name. This is a type annotation.
let city: string = "Lisbon";let population: number = 545000;let isCapital: boolean = true;console.log(city, population, isCapital);Type names are written in lowercase. string is the type, while "Lisbon" is a value of that type.
TypeScript holds you to it
Once a variable has a type, every value you put in it must match. Here, lives is a number, so text isn't allowed.
let lives: number = 3;lives = 2;lives = "two";Line 2 is fine, because 2 is a number. Line 3 tries to put a string in a number box. "Not assignable" is TypeScript's way of saying "this value doesn't fit here".
Types for values that come later
Sometimes you make a variable before you know its value. Give it a type, and fill it in later. TypeScript makes sure you don't use it before then.
let winner: string;const scores = [12, 30, 25];if (scores[1] > 20) { winner = "Sam";} else { winner = "Ana";}console.log(`The winner is ${winner}.`);Without : string, TypeScript couldn't know what winner is meant to hold.
Types follow the value through your code
Types don't only guard the = sign. TypeScript also checks how each value is used. A number can be multiplied, and a string has string methods like toUpperCase().
const price: number = 4.5;const item: string = "coffee";console.log(item.toUpperCase(), price * 2);Using a string method on price would be a type error, even though no = is involved.
null and undefined
Two more types each have a single value. undefined means "no value yet", and null means "nothing here, on purpose". With TypeScript's normal settings, a string variable can't hold either of them.
let nickname: string = "Ace";nickname = null;This stops a whole family of bugs, where code expects text and finds nothing. You'll learn how to allow null when you need it in a later topic.
String or Number. These are names of JavaScript objects, not the types you want. TypeScript accepts them, but they behave differently in places. Always use the lowercase string, number and boolean.let title: String = "Home";let other: string = title;Try it yourself
Run the code in the editor and answer 8 practice questions on adding types. It's free, you only need an account.