TypeScript variable declaration

Posted by acoole on Tue, 23 Nov 2021 02:28:43 +0100

TypeScript variable declaration
A variable is a convenient placeholder for referencing a computer's memory address.

We can think of variables as containers for storing data.

Naming rules for TypeScript variables:
1: Variable names can contain numbers and letters.
2: Except underline_ No other special characters, including spaces, can be included except the dollar and $symbols.
3: Variable names cannot start with numbers.

Variables must be declared before use. We can use var to declare variables.
We can declare variables in the following four ways:
Declare the type and initial value of the variable:

var [Variable name] : [type] = value;

For example:

var uname = "Runoob";

The declared variable has no type and initial value set. The type can be any type. The default initial value is undefined:

var [Variable name];

For example:

var uname;


var uname:string = "Runoob";
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("Grade of the second subject: "+score2)
console.log("Total score: "+sum)

**Note: * * do not use name for the variable, otherwise it will have the same name as the name attribute under the global window object in the DOM.

Compile the above code with tsc command to obtain the following JavaScript code:

var uname = "Runoob";
var score1 = 50;
var score2 = 42.50;
var sum = score1 + score2;
console.log("name: " + uname);
console.log("First subject score: " + score1);
console.log("Grade of the second subject: " + score2);
console.log("Total score: " + sum);

The output result of executing the JavaScript code is:

name: Runoob
 First subject score: 50
 Grade of the second subject: 42.5
 Total score: 92.5

TypeScript follows strong typing. If different types are assigned to variables, compilation errors will occur, as shown in the following example

var num:number = "hello"     // This code will compile incorrectly

Type Assertion
Type assertions can be used to manually specify the type of a value, allowing variables to change from one type to another.

Syntax format:



value as type


var str = '1' 
var str2:number = <number> <any> str   //str and str2 are string types

How does TypeScript determine whether a single assertion is sufficient
When s type is a subset of T type, or T type is a subset of S type, s can be successfully asserted as t. This is to provide additional security when making type assertions. Completely groundless assertions are dangerous. If you want to do so, you can use any.

It is not called type conversion because conversion usually means some kind of runtime support. However, type assertion is purely a compile time syntax, and it is also a way for the compiler to provide information on how to analyze code.

After compilation, the above code will generate the following JavaScript code:

var str = '1';
var str2 = str;  //str and str2 are string types

The execution output is:


Type inference
When the type is not given, the TypeScript compiler uses type inference to infer the type.

If a type cannot be inferred due to lack of declaration, its type is treated as the default dynamic any type.

var num = 2;    // Type inferred as number
console.log("num The value of the variable is "+num); 
num = "12";    // Compilation error

The first line of code declares the variable num = and sets the initial value to 2. Note that the variable declaration does not specify a type. Therefore, the program uses type inference to determine the data type of the variable. The first assignment is 2 and num is set to type number.

In the third line of code, when we set the value of string type for the variable again, there will be a compilation error. Because the variable is already set to type number.

error TS2322: Type '"12"' is not assignable to type 'number'.

Variable scope
The variable scope specifies the location of the variable definition.

The availability of variables in a program is determined by the variable scope.

TypeScript has the following scopes:

Global scope - global variables are defined outside the 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 the class's methods. This variable can be accessed through the object of the class. Class variables can also be static. Static variables can be accessed directly through the class name.

Local scope − local variable. A local variable can only be used in a code block (such as a method) that declares it.

The following examples illustrate the use of three scopes:

var global_num = 12          // global variable
class Numbers { 
   num_val = 13;             // Instance variable
   static sval = 10;         // Static variable
   storeNum():void { 
      var local_num = 14;    // local variable
console.log("The global variable is: "+global_num)  
console.log(Numbers.sval)   // Static variable
var obj = new Numbers(); 
console.log("Instance variable: "+obj.num_val)

The above code is compiled into JavaScript using tsc command. The code is:

var global_num = 12; // global variable
var Numbers = /** @class */ (function () {
    function Numbers() {
        this.num_val = 13; // Instance variable
    Numbers.prototype.storeNum = function () {
        var local_num = 14; // local variable
    Numbers.sval = 10; // Static variable
    return Numbers;
console.log("The global variable is: " + global_num);
console.log(Numbers.sval); // Static variable
var obj = new Numbers();
console.log("Instance variable: " + obj.num_val);

Execute the above JavaScript code, and the output result is:

The global variable is: 12
 Instance variable: 13

If we call the local variable local outside the method_ Num, an error will be reported:

error TS2322: Could not find symbol 'local_num'.

Topics: Javascript Front-end TypeScript