Ts Variables
Variables are convenient placeholders used to reference computer memory addresses.
We can think of variables as containers for storing data.
TypeScript variable naming rules:
* Variable names can contain numbers and letters.
* They cannot contain other special characters, including spaces, except for the underscore _ and dollar $ symbols.
* Variable names cannot start with a number.
Variables must be declared before use. We can use `var` to declare variables.
We can declare variables in the following four ways:
Declare the variable's type and initial value:
var : = value;
For example:
var uname:string = "";
Declare the variable's type without an initial value; the variable value will be set to `undefined`:
var : ;
For example:
var uname:string;
Declare a variable with an initial value but without setting the type; the variable can be of any type:
var = value;
For example:
var uname = "";
Declare a variable without setting the type or initial value; the type can be any type, and the default initial value is `undefined`:
var ;
For example:
var uname;
### Example
var uname:string ="";
var score1:number =50;
var score2:number =42.50
var sum = score1 + score2
console.log("Name: "+uname)
console.log("First subject score: "+score1)
console.log("Second subject score: "+score2)
console.log("Total score: "+sum)
**Note:** Do not use `name` as a variable name, as it will conflict with the `name` property of the global `window` object in the DOM.
Compile the above code using the `tsc` command to get the following JavaScript code:
var uname = ""; var score1 = 50; var score2 = 42.50; var sum = score1 + score2; console.log("Name: " + uname); console.log("First subject score: " + score1); console.log("Second subject score: " + score2); console.log("Total score: " + sum);
Executing this JavaScript code outputs:
Name: TutorialFirst subject score: 50Second subject score: 42.5Total score: 92.5
TypeScript follows strong typing. Assigning a different type to a variable will cause a compilation error, as shown in the following example:
var num:number = "hello" // This code will cause a compilation error
* * *
## Type Assertion
Type Assertion can be used to manually specify the type of a value, allowing a variable to be changed from one type to another.
Syntax:
value
or:
value as type
### Example
var str = '1'var str2:number = str console.log(str2)
### How TypeScript Determines if a Single Assertion is Sufficient
When type S is a subtype of type T, or type T is a subtype of type S, S can be successfully asserted to T. This provides additional safety during type assertions. Completely baseless assertions are dangerous; if you want to do that, you can use `any`.
It is not called **type conversion** because conversion usually implies some form of runtime support. However, type assertion is purely a compile-time syntax and also a way to provide the compiler with information on how to analyze the code.
After compilation, the above code generates the following JavaScript code:
var str = '1'; var str2 = str; console.log(str2);
The output is:
1
* * *
## Type Inference
When the type is not specified, the TypeScript compiler uses type inference to deduce the type.
If the type cannot be inferred due to a lack of declaration, its type is considered the default dynamic `any` type.
var num = 2; console.log("The value of num variable is "+num); num = "12"; console.log(num);
* The first line declares the variable `num` and sets its initial value to 2. Note that the variable declaration does not specify a type. Therefore, the program uses type inference to determine the variable's data type. Since the first assignment is 2, **num** is set to the `number` type.
* In the third line, when we set a string value to the variable again, a compilation error occurs. This is because the variable has already been set to the `number` type.
error TS2322: Type '"12"' is not assignable to type 'number'.
* * *
## Variable Scope
Variable scope specifies where a variable is defined.
The availability of a variable in a program is determined by its scope.
TypeScript has the following scopes:
* **Global Scope** β Global variables are defined outside of any program structure and can be used anywhere in your code.
* **Class Scope** β This variable can also be called a **field**. Class variables are declared inside a class but outside of its methods. This variable can be accessed through an object of the class. Class variables can also be static; static variables can be accessed directly through the class name.
* **Local Scope** β Local variables can only be used within the code block (e.g., a method) where they are declared.
The following example illustrates the use of the three scopes:
var global_num = 12 class Numbers{num_val = 13; static sval = 10; storeNum():void{var local_num = 14; }}console.log("Global variable: "+global_num)console.log(Numbers.sval)var obj = new Numbers(); console.log("Instance variable: "+obj.num_val)
The above code is compiled into JavaScript code using the `tsc` command as follows:
var global_num = 12; var Numbers = (function(){function Numbers(){this.num_val = 13; }Numbers.prototype.storeNum = function(){var local_num = 14; }; Numbers.sval = 10; return Numbers; }()); console.log("Global variable: " + global_num); console.log(Numbers.sval); var obj = new Numbers(); console.log("Instance variable: " + obj.num_val);
Executing the above JavaScript code outputs:
Global variable: 1210Instance variable: 13
If we call the local variable `local_num` outside the method, an error will occur:
error TS2322: Could not find symbol 'local_num'.
YouTip