Introduction
A variable is a uniquely named location used to store data in any programming language. In Typescript, the variable must be declared before being used, using the keyword let or var. The syntax for declaring variables in Typescript is a little different from other languages and looks something like this,
var [variable_name] : [type_of_variable] = [value] ;
The variable may or may not have a value and type initialized.
For example
var name: string = “Ninja”;
var name: string;
var name = “Ninja”;
var name;
All of these are correct methods of initializing a variable.
Type Assertion refers to changing the variable from one type to another explicitly. In Typescript, we refer to this as Type Assertion, whereas in some programming languages, it is also referred to as Explicit Type Conversion or Type Casting. Type Assertion can be performed using three methods,
- Using Angular (<>) Brackets
- Using “as” Keyword
- Type Assertion with Objects
Using Angular(<>) Brackets
This is the most basic and most commonly used type of Assertion in Typescript. The syntax is quite simple and looks like,
var num:any = 1111;
var assertedNum = <number> num;
console.log("Type of variable assertedNum: "+ typeof(assertedNum));
The type to which the variable is supposed to be converted is mentioned in angular brackets before the value. In the above example, we converted the variable “num” with data type any to “assertedNumber” with data type number