Open In App

Variables in TypeScript

The variable is a named place in memory where some data/value can be stored. They serve as containers for storing data values, allowing to store numeric, string, boolean, and other types of information. In this TypeScript Variable Article, we'll learn how to declare, manipulate, and utilize variables in TypeScript.

Variable Declaration in TypeScript

1. var, let, and const

In TypeScript, we have three primary keywords for variable declaration:

2. Rules have to be followed:

3. Ways to Variable declaration:

We can declare a variable in multiple ways like below:

  • var Identifier:Data-type = value;
  • var Identifier: Data-type;
  • var Identifier = value;
  • var Identifier;
  • Examples:

    Variable declarationDescription
    var name:number = 10;Here name is a variable which can store only Integer type data.
    var name:number;Here name is a variable which can store only Integer type data. But by default its value set to undefined.
    var name = 10;Here while declaring variable we are not specifying data-type. Therefore compiler decide its data type by seeing its value i.e. number here.
    var name;Here while declaring variable we are not specifying data-type as well as we are not assigning any value also. Then compiler takes its data type as any. Its value is set to undefined by default.

    3.  Type Annotations

    TypeScript enhances variables with type annotations, making it a strongly typed language. When declaring a variable, you can specify its type explicitly. 

    Example:

    let name: string = 'Amit';
    let age: number = 25;
    const country: string = 'Noida';

    4. Variable scopes in TypeScript:

    Here scope means the visibility of variable. The scope defines that we are able to access the variable or not. TypeScript variables can be of the following scopes:

    Example:

    let global_var: number = 10; // global variable
    
    class Geeks {
        geeks_var: number = 11; // class variable
        assignNum(): void {
            let local_var: number = 12; // local variable
        }
    }
    
    console.log("Global Variable: " + global_var);
    
    let obj = new Geeks();
    console.log("Class Variable: " + obj.geeks_var);
    

    Output:

    Global Variable: 10
    Class Variable: 11
    Article Tags :