TypeScript Variables

By   Calendar icon Aug 10, 2020   Level 1 icon


Here we explain what a variable is in TypeScript and give some examples. Variables are used to represent in memory data of type number, … Their use must respect the type compatibility check.


Tags: TypeScript

As in many programming languages, a variable represents a named in-memory location to store values. The value contained in the memory space, also called the contents of the variable can change while the program is running.

As with an identifier the name of a variable must consist of alphanumeric characters, cannot begin with a number and must not contain symbols. They can only contain letters, numbers, and symbols $ and _. Moreover, they are case sensitive.

Assigning a value to a variable means storing a value to a variable. To assign a value we use the equal sign.

Declaring variables in TypeScript

To declare a variable in TypeScript, we use the keyword let instead of var. A variable can be initialized when it is declared, and in this case, it is not necessary to specify the type. When the variable is not initialized, it is set to undefined.

Let us see how to declare a variable for each base type.

Variables of type Boolean

let isOdd:boolean=true;

or more simply:

let isOdd=true;

Variables of type number

There is only one type to represent the numbers in TypeScript: the number type.

But it is possible to assign values in different formats to a variable of type number. This data will be converted into real floating stored on 64-bits.

let f:number=0.8e-11;
let d: number = -8;
let h: number = 0xff0a; //hexadecimal number
let b: number = 0b0010; //binary
let o: number = 0o654; //octal

String Variables

String-type variables are used to store textual data. To represent a literal string, the text is surrounded by double quotes (") or single quotes (').

let s:string="ABCDEF";

Tuple type Variables

// Declare a tuple type variable
let x: [boolean, string];
// Initialize x
x = [true, "John is policeman"];

Enum type Variables

enum Metal {Gold, Copper, Iron, Silver};
    let c: Coin = Metal.Copper;

Array-type Variables

let years: number[] = [2000, 2017, 2018];
let years: Array<number> = [2000, 2017, 2018];