header ad

Variables in TypeScript

Variables in TypeScript

Variables in TypeScript – A variable is defined as “a named space in memory” where values are stored. In other words, it serves as a container for program values. The variable in TypeScript has the same naming convention as a JavaScript variable declaration. These are the guidelines:

  • 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.

header ad

Variable declaration

In TypeScript, the type syntax for declaring a variable is to use a colon (:) after the variable name, followed by the type. To declare a variable, we use the var keyword, just as in JavaScript.

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.
var [identifier];  

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

  • Variables
  • Constants
  • Data Types
  • Strings
  • Numbers
  • Boolean
  • Object Types

Leave a Comment

Your email address will not be published.