Easy Tutorial
❮ Home Ts Quiz ❯

TypeScript Variable Declarations

A variable is a convenient placeholder that refers to a computer memory address.

We can think of variables as containers for storing data.

TypeScript variable naming rules:

-

Variable names can contain numbers and letters.

-

Apart from underscores _ and dollar $ symbols, they cannot contain other special characters, including spaces.

-

Variable names cannot start with a number.

Variables must be declared before use, and we can use var to declare variables.

We can declare variables using the following four methods:

Declare the variable's type and initial value:

var [variableName]: [type] = value;

For example:

var uname: string = "tutorialpro";

Declare the variable's type but without an initial value, which will be set to undefined:

var [variableName]: [type];

For example:

var uname: string;

Declare the variable with an initial value but without a type, making it of any type:

var [variableName] = value;

For example:

var uname = "tutorialpro";

Declare the variable without a type and initial value, making it of any type with a default initial value of undefined:

var [variableName];

For example:

var uname;

Example

var uname: string = "tutorialpro";
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 for variables as it conflicts with the name attribute in the global window object in the DOM.

Compiling the above code with the tsc command yields the following JavaScript code:

var uname = "tutorialpro";
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: tutorialpro
First subject score: 50
Second subject score: 42.5
Total score: 92.5

TypeScript follows strong typing, and assigning different types to variables will result in a compile error, as shown in this example:

var num: number = "hello"; // This code will compile with an error

Type Assertion

Type assertion allows you to manually specify the type of a value, enabling a variable to change from one type to another.

Syntax:

<type>value

or:

value as type

Example

var str = '1';
var str2: number = <number><any>str; // str, str2 are of type string
console.log(str2);

How TypeScript Determines if a Single Assertion is Sufficient

When type S is a subset of type T, or type T is a subset of type S, S can be successfully asserted to T. This provides additional safety when asserting types, as unfounded assertions can be dangerous. If you wish to do so, you can use any.

Type assertion is not called "type casting" because casting typically implies some runtime support. However, type assertion is purely a compile-time syntax and a method for the compiler to analyze code.

Compiling the above code generates the following JavaScript code:

var str = '1';
var str2 = str; // str, str2 are of type string
console.log(str2);

Executing this outputs:

1

Type Inference

When a type is not provided, TypeScript's compiler uses type inference to determine the type.

If the type cannot be inferred due to lack of declaration, it is considered to be of the dynamic any type.

var num = 2; // Type inferred as number
console.log("Value of num variable: " + num);
num = "12"; // Compile error
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 infers the data type of the variable, setting num to number type due to the initial assignment of 2.

-

On the third line, assigning a string type value to the variable results in a compile error because the variable has already been set to number type.

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

Variable Scope

Variable scope specifies where the 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 the program structure and can be used anywhere in the code.

-

Class Scope − These variables can also be called fields. Class variables are declared within a class but outside methods. They can be accessed through class objects. Static variables can be accessed directly using the class name.

-

Local Scope − Local variables are only usable within the block (e.g., method) where they are declared.

The following example illustrates the use of these 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("Global variable: " + global_num);
console.log(Numbers.sval); // Static variable
var obj = new Numbers();
console.log("Instance variable: " + obj.num_val);

Compiling the above code with the tsc command generates the following JavaScript code:

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("Global variable: " + global_num);
console.log(Numbers.sval); // Static variable
var obj = new Numbers();
console.log("Instance variable: " + obj.num_val);

Executing this JavaScript code outputs:

Global variable: 12
10
Instance variable: 13

Attempting to use the local variable local_num outside its method results in an error:

error TS2322: Could not find symbol 'local_num'.
❮ Home Ts Quiz ❯