27.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;

27.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;

27.2.2. string

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

let variableName: string = "10";

27.2.3. boolean

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

let variableName: boolean = true;

27.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// In JavaScript, we have:
 2
 3let spaceShuttleName = "Determination";
 4let shuttleSpeed = 17500;
 5let distancetoMars = 225000000;
 6let distancetoMoon = 384400;
 7let milesperKilometer = 0.621;
 8
 9// The same declarations in TypeScript would be:
10
11let spaceShuttleName: string = "Determination";
12let shuttleSpeed: number = 17500;
13let distancetoMars: number = 225000000;
14let distancetoMoon: number = 384400;
15let milesperKilometer: number = 0.621;

27.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";