TypeScript Variables

By Dec 09, 2017


TypeScript Variables


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's 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];





KodFor Privacy Policy