How to Declare Variables in TypeScript ?

In TypeScript, a variable can be defined by specifying the data type of the value it is going to store. It will store the values of the specified data type only and throws an error if you try to store the value of any other data type. You can use the colon syntax(:) to declare a typed variable in TypeScript. You need to declare variables in this format because TypeScript is a statically typed language not a loosely typed language that is why you need to explicitly type the variables before assigning them values of a particular type.

Syntax:

const variable_name: data_type = value;

Example: The below code defines a variable with specified data types in TypeScript.

Javascript




const var1: string = "GFG";
const var2: number = 35;
console.log(var1);
console.log(var2);


Output:

"GFG"
35

Contact Us