- The variable name must be made up of letters or digits.
- The name of a variable cannot begin with a digit.
- Except for the underscore (_) and dollar ($) symbol, they cannot contain spaces or special characters.
In ES6, the let and const keywords can be used to define variables. These variables have similar variable declaration and initialization syntax, but their scope and usage are different. It is always advised in TypeScript to define a variable with the let keyword because it ensures type safety.
You have four possibilities when declaring a variable:
- Declare the type and value in a single statement.
var [identifier] : [type-annotation] = value;
- Declare the type but leave the value blank. The variable will be set to undefined in this situation.
var [identifier] : [type-annotation];
- Declare the value without specifying a type. The variable will then be set to any value.
var [identifier] = value;
- Neither a value nor a type should be declared. The variable’s data type will be any in this scenario, and it will be initialised to undefined.
TypeScript Variable Scope
The term “scope” refers to a variable’s visibility. The scope determines whether or not we may access the variable. Variables in TypeScript can have one of the following scopes:
- Global Scope – Outside of the programming constructs, global variables are declared. These variables can be accessed at any point in your programme. This is referred to as Global Scope.
- Local Scope – As the names indicate, local variables are defined within constructions like as methods, loops, and so on. Local variables can only be accessed within the construct in which they were declared.
- Class Scope – Class variables are declared outside of the methods but within the class. The class’s object can be used to access these variables. The class name is used to access static fields. Fields are another term for these variables. Fields can be both dynamic and static.
In This Module
- Data Types
- Object Types