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;
number
¶When declaring a variable and using the number
type, we add number
to the variable declaration, like so:
let variableName: number = 10;
string
¶When declaring a string
, we want to use the string
keyword.
let variableName: string = "10";
boolean
¶The boolean
keyword should be used when declaring a variable of the boolean
type.
let variableName: boolean = true;
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;
Question
The correct declaration of the variable, astronautName
, that holds the value, "Sally Ride"
, is:
let astronautName = "Sally Ride";
let astronautName = string: "Sally Ride";
let astronautName: string = "Sally Ride";
string astronautName = "Sally Ride";