This blog will explain TypeScript and the way how to use it.
What is TypeScript?
Microsoft created the free and open-source programming language called “TypeScript”. It is a superset of JavaScript, which signifies that it includes all of JavaScript’s features as well as extra features such as “static typing”, “classes”, “interfaces”, and many more. These features help developers to write code that is more manageable and scalable.
In TypeScript, types are explicitly declared at compile time which helps to detect errors immediately in the developing process and makes code more secure and reliable. This compilation phase creates plain JavaScript code that can be executed in any browser or environment.
How Does TypeScript Differ From JavaScript?
One of the primary differences between JavaScript and TypeScript is how they deal with types. Variables in JavaScript can store any type of value, and the variable’s type can change at runtime. While in TypeScript the variables can be declared with a particular type, and the type of a variable cannot be changed/modified at runtime.
Example
In JavaScript, when we declare a variable there is no need to explicitly define a variable type. It can store any type of data whether it is a string, number, or a Boolean type:
xyz = 11
xyz = true
In TypeScript, the variable is declared as:
The “string” indicates that the variable “xyz” will only store string type value. If we attempt to assign a value of any other type such as a Boolean or number, it will result in a compile-time error.
How to Use TypeScript?
For using TypeScript, follow the given steps:
- First, you have to install “Node.js” on your computer using this official link.
- After that open the command prompt and install TypeScript utilizing the given command:
- Then, create a file with the “.ts” extension and write/add the TypeScript code to it.
- Now, open the command prompt and execute the given command to transpile the TypeScript code to JavaScript code:
- After compiling TypeScript code to JavaScript, link the “.js” file to the HTML file using the “src” attribute of the <script> tag:
- Lastly, open/run the HTML file in a web browser and the JavaScript code will be executed.
Note: Another way to execute the TypeScript file is using the “VS Terminal”. Open the terminal using the “ctrl+shift+`” and run the given command:
We have compiled all the essential instructions relevant to TypeScript and how to use it.
Conclusion
TypeScript is an extended form of JavaScript that includes all of JavaScript’s features as well as extra features like “static typing”. Due to this feature, the types are explicitly declared at compile time while in JavaScript, the variable’s type can change at runtime. For installing TypeScript on your computer, first, you need to install “Node.js“, after that run the “npm install -g typescript” command. This blog explained TypeScript and the way how to use it.