28.2. Declaring and Using Variables

Since TypeScript is statically typed, the type of value is added to the variable declaration. However, we will still use our let and const keywords where appropriate.

The general format of a variable declaration is:

let variableName: type = value;

28.2.1. number

When declaring a variable and using the number type, we add number to the variable declaration, like so:

let variableName: number = 10;

28.2.2. string

When declaring a string, we want to use the string keyword.

let variableName: string = "10";

28.2.3. boolean

The boolean keyword should be used when declaring a variable of the boolean type.

let variableName: boolean = true;

28.2.4. Examples

Let's use some familiar variable declarations to compare between what we know how to do in JavaScript and what we are now learning about TypeScript.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// In JavaScript, we have:

let spaceShuttleName = "Determination";
let shuttleSpeed = 17500;
let distancetoMars = 225000000;
let distancetoMoon = 384400;
let milesperKilometer = 0.621;

// The same declarations in TypeScript would be:

let spaceShuttleName: string = "Determination";
let shuttleSpeed: number = 17500;
let distancetoMars: number = 225000000;
let distancetoMoon: number = 384400;
let milesperKilometer: number = 0.621;

28.2.5. Check Your Understanding

Question

The correct declaration of the variable, astronautName, that holds the value, "Sally Ride", is:

  1. let astronautName = "Sally Ride";

  2. let astronautName = string: "Sally Ride";

  3. let astronautName: string = "Sally Ride";

  4. string astronautName = "Sally Ride";