Variable declaration is important part of any programming language.Variable declaration in TypeScript is more important since it provides some improvements over JavaScript when declaring variable.
TypeScript provides different ways of declaring variables.We can declare a variable using these ways depending on the scenario.
Following are the important variable declarations
- var
- let
- const
- declare
We can briefly describe these variables using the following
Variable declaration in TypeScript
let variables
let is part of ECMAScript 6.let is used for declaring variables just like the var keyword.There is an important difference between the let and var keywords.
The difference is in the scope where the variable is visible.The scope of the variable declared with the let keyword is the enclosing block while the scope of the var variable is the enclosing function.
In the following example the variable result is declared inside the if block.But result is accessible not only within if block but anywhere in the
function.This is because variable declared using the var keyword has the same scope as the containing block which is function here.
function getResult(id:number) { if (id=1) { var result = "pass"; } return "fail"; }
This could be problem in few scenarios as it could result in unexpected results.Suppose we call the above method with the following parameters:
- getResult(1) this is correct as the variable result is accessible outside the if block.It can be accessed from anywhere within the getResult() fucntion.
- getResult(0) this will throw error as result is undeclared in this case.
Another difference between var and let is when a variable can be accessed.We can not use a variable declared with the let keyword before it is declared.
For example the following code will result in error.This is because we are accessing the temp variable before it is declared.
temp=1; let temp;
const variables
const variable can not be changed after it is declared.It must be initialized when it is declared.It is used in scenarios where we don’t want to change the value of the variable after it is declared.
For example if we declare a const variable as
const fixed = 2;
then we can not reassign the variable.Following will result in error.
fixed=3;
const is part of ECMAScript 6.
Ambient variables
Remember that TypeScript is a superset of JavaScript and it can be used with JavaScript frameworks.For example we can use the jQuery methods in typescript.
There is one problem while using the objects in other JavaScript frameworks. TypeScript will not understand these since there is no associated typescript declaration file (.ts file).
The variable in this scenario exists in the global namespace but TypeScript will give compilation error.Solution in such scenarios is to use declare keyword for accessing these objects.
declare var library1;
Variable declaration in TypeScript can be used to prevent many runtime errors.
Leave a Reply