- 4 years ago
- Afaq Arif
- 10,187 Views
-
3
In this chapter, we will discuss in detail that how to use variables in TypeScript. We will also learn about variable scope in TypeScript.
A variable is “a named space in the memory” that is used to save values. In simple, it acts as a box for the values in a program. TypeScript variables must follow the JavaScript naming rules.
- Variable names can keep alphabets and numeric digits.
- They cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
- Variable names cannot start with a digit.
We must declare variables before using them. We will use the var keyword to declare variables.
Variable Declaration in TypeScript
We use the type syntax to declare a variable in TypeScript. It consists of a colon (:) after the variable name, followed by its type. The var keyword will use to declare a variable in TypeScript same as JavaScript.
When you declare a variable, you have four options.
- Declare its type and value in one statement.
- Declare its type but no value. In this case, the variable will be undefined.
- Declare its value but no type. The variable type sets to the data type of the assigned value.
- Declare neither value not type. In this case, the data type of the variable can be any and can set to undefined.
The following table shows the valid syntax for variable declaration as discussed above.
S.No. | Variable Declaration Syntax & Description |
---|
1. | var name:string = ”mary”The variable saves a value of type string |
2. | var name:string;The variable is a string variable. The variable’s value is set to undefined by default |
3. | var name = ”mary”The variable’s type is inferred from the data type of the value. Here, the variable is of the type string |
4. | var name;The variable’s data type is any. Its value is set to undefined by default. |
Example: Variables in TypeScript
var name:string = "John";
var score1:number = 50;
var score2:number = 42.50
var sum = score1 + score2
console.log("name"+name)
console.log("first score: "+score1)
console.log("second score: "+score2)
console.log("sum of the scores: "+sum)
The following JavaScript code will run on compiling.
//Generated by typescript 1.8.10
var name = "John";
var score1 = 50;
var score2 = 42.50;
var sum = score1 + score2;
console.log("name" + name);
console.log("first score: " + score1);
console.log("second score : " + score2);
console.log("sum of the scores: " + sum);
The above program will show the following output.
name:John
first score:50
second score:42.50
sum of the scores:92.50
If we try to give a value that is not of the same type, the TypeScript compiler will run errors. Therefore, TypeScript follows Strong Typing. The Strong typing syntax guarantees that the types mentioned on either side of the assignment operator (=) are the same. This is why the following code will result in a compilation error.
var num:number = "hello" // will result in a compilation error
Type Assertion in TypeScript
TypeScript permits you to change a variable from one type to another, a process called Type Assertion. The syntax is to put the target type between < > symbols and place it in front of the variable. The following example explains this concept.
Example
var str = '1'
var str2:number = <number> <any> str //str is now of type number
console.log(typeof(str2))
You can see the change in the variables’ data type by hanging the mouse pointer over the type assertion statement in Visual Studio Code. It allows the assertion from type S to T to succeed if either S is a subtype of T or T is a subtype of S.
The main reason we can not call it “type casting” is that casting normally suggests some kind of runtime support while “type assertions” are completely a compile-time construct. It also gives hints to the compiler on how you need your code to be examined.
The following JavaScript code will generate on compiling.
"use strict";
var str = '1';
var str2 = str; //str is now of type number
console.log(typeof (str2));
It will show the following output.
Inferred Typing in TypeScript
This feature is optional as Typescript is strongly typed. You can declare a variable without a type because it encourages the dynamic typing of variables. In such cases, the compiler controls variable type based on the value given to it. TypeScript finds the first variable usage within the code. It decides the type to which it has been originally set and then takes the same type for this variable in the rest of your code block.
The same explains in the following code part.
Example: Inferred Typing
var num = 2; // data type inferred as number
console.log("value of num "+num);
num = "12";
console.log(num);
In the above code part.
- The code announces a variable and sets its value to 2. Observe that the variable declaration doesn’t define the data type. Therefore, the program uses inferred typing to decide the data type of the variable. It gives the type of the first value to which variable is originally assigned. In this case, num is set to the type number.
- If the code tries to put the variable’s value to a string, the compiler will throw an error as the variable’s type is already set to number.
It will show the following output.
error TS2011: Cannot convert 'string' to 'number'.
TypeScript Variable Scope
The scope of a variable is stated where the variable defines. The scope controls the accessibility of a variable inside a program. TypeScript variables can be of the following scopes.
- Global Scope − Global variables are outside the programming setup. You can call these variables from anywhere within your code.
- Class Scope − These variables are also called fields. You can call these variables inside the class but outside the methods. These variables can be accessed using the object of the class. Fields can also be static and can be called using the class name.
- Local Scope − Local variables declared inside the setups like methods, loops, etc. We can access these variables only inside the setup where they are declared.
The following example shows variable scopes in TypeScript.
Example: Variable Scope
var global_num = 12 //global variable
class Numbers {
num_val = 13; //class variable
static sval = 10; //static field
storeNum():void {
var local_num = 14; //local variable
}
}
console.log("Global num: "+global_num)
console.log(Numbers.sval) //static variable
var obj = new Numbers();
console.log("Global num: "+obj.num_val)
The following JavaScript code will generate on compiling.
var global_num = 12; //global variable
var Numbers = (function() {
function Numbers() {
this.num_val = 13; //class variable
}
Numbers.prototype.storeNum = function() {
var local_num = 14; //local variable
};
Numbers.sval = 10; //static field
return Numbers;
}());
console.log("Global num: " + global_num);
console.log(Numbers.sval); //static variable
var obj = new Numbers();
console.log("Global num: " + obj.num_val);
It will show the following output.
Global num: 12
10
Global num: 13
If you try to access the local variable outside the method, it will show a compilation error.
error TS2095: Could not find symbol 'local_num'.
- 4 years ago
- Afaq Arif
- 10,187 Views
-
3