Welcome to today’s session on TypeScript programming, where we will take a closer look at TypeScript variables. Just as a container might hold various items, variables in TypeScript be used to store data of different types. In this lesson, our main focus will be on understanding what variables are, defining them, assigning values, grasping proper naming conventions, and finally displaying the values stored within these variables. Isn’t it exciting? Let's embark on this illuminating journey!
Imagine a box. This box can contain items like books, snacks, or even small gadgets. Variables in TypeScript are akin to such boxes—they store different types of values. The exciting part is that, similar to changing the contents of the box, the values variables hold can also be changed. Now let's see this in action with some code:
In this example, myVariable initially holds a greeting message and then gets re-assigned to a string containing a numerical value.
In TypeScript, defining a variable and assigning it a value can be done using the let, const, or var keywords, followed by the variable name and an optional type annotation. The let and const keywords are part of TypeScript's newer syntax and offer block-scoped binding, contrasting with var, which is function-scoped. A crucial difference to note is that variables declared with const are meant to be constants, meaning once assigned a value, it cannot change throughout the code.
Here are properly formed variable names and assignments:
And here is how you would define a constant variable:
