In the previous few chapters of the TypeScript Tutorial series we have learned how to install TypeScript and then begin with creating a simple HelloWorld application. We have also learned about TypeScript configuration file (tsconfig.json
).
In this chapter we will learn various ways to declare variables in TypeScript. Continue reading to learn more about it.
👉 TypeScript Tutorial - Getting started with TypeScript
Declaring variables with "var" keyword
Just like JavaScript, you can also define variables in TypeScript using the keyword var
. For example, var message = "Hello World!";
. Defining variables using the var
keyword has some problems and most of the developers face this issue. Let's take few examples to understand it in better way.
You can define a variable inside a block and use it outside the scope, like this:
function GetValue(initialize: boolean) {
if (initialize) {
var value = 100;
}
return value;
}
GetValue(true); // returns "100"
GetValue(false); // returns "undefined"
Using the var
keyword, you can declare the same variable multiple times within the same code block. For example, the following code will execute without any error:
function GetValue(value, condition) {
var value = 10;
...
...
var value = 25; // no error
...
...
if (condition) {
var value = 100; // no error
...
}
}
Declaring variables with "let" keyword
To overcome the problems that arises with variable declaration using the var
keyword, TypeScript introduces variable declaration using let
keyword. You can write the let
statements the same way that you write the var
statements. For example, let message = "Hello World!";
.
Unlike var
, the let
statement uses block-scoping. That means, if you declare a variable with let
keyword in a function or a block, the scope of the variable will be limited to the same function or code block and won't be accessible outside of their nearest containing block.
function GetValue(initialize: boolean) {
if (initialize) {
var value = 100;
}
return value; // error
}
It's also a point to note that, you can't redeclare a variable using let
keyword within the same scope, which was a problem with var
declaration. The following code will throw error during compile time:
function GetValue(condition) {
let value = 10;
...
...
let value = 25; // ERROR: re-declaration of "value"
...
...
if (condition) {
let value = 100;
...
}
}
Declaring variables with "const" keyword
You can also declare variables using the const
keyword. For example, const message = "Hello World!";
. The const
keyword acts like let
but with a difference that their values cannot be changed after they are initialized and hence you cannot re-assign values to them.
👉 TypeScript Tutorial - Getting started with TypeScript
CodeProject