Introduction
In this article, we will learn how to declare variables and use type annotations in Typescript. If you are new to Typescript, I will recommend you to check the previous article of this series:
Declare variables in Typescript
Before using the type Annotation, let’s take a look at declaring a variable using var, let, and const keywords.
var, let and const
var is globally available in function block and is hoisted to the top of the function.

In the example mentioned above, we declared the name variable in if condition, but we are able to access the same variable out of the if condition because var is globally available in a function block.
It is let, which is accessible in the nearest enclosing block (or globally, if declared outside of a function). If we try to access the variable outside the block, we will get the reference error.
Let’s move the console.log (name) statement inside if condition and run the Application. It will print the name on the console.

We can redeclare var in the same function scope, but cannot declare let and const.
In the example given below, we got an error, which states we cannot redeclare the block-scoped variable.

In the case of const, we even cannot assign again, as it is constant or read-only property.
Type annotation in Typescript

In the image given above, the first syntax is with type-annotation as well as value. The second syntax is with type-annotation, but no value (have undefined value) and third syntax is without the type-annotation but has the value.
Typescript allows us to declare variables with the specific data type and can be classified into Built-In types (ex. String, number, Boolean, etc.) and user-defined types (ex. Array, Class, interface, enum, etc.). Any data type is the super of all the data types in Typescript. It is the default data type for the variables and the function.



We can even override the value of each enumerator of an enum.
Tuples
Tuple represents the heterogeneous collection of values. Tuple values are individually called the items. In the example given below, we have created a tuple, which can hold the values of the typed string and the number.


If we try to store a value of another type, which is not specified, then we will get an error.
I hope this will help you. Thanks.

Join the conversation! Your thoughts help the community grow.