Why Use TypeScript?
- It helps in avoiding errors in the code.
- Has code structuring and object-oriented programming techniques.
- Supports ES6.
- It offers rich IDE with autocomplete and code navigation features.
- Interfaces, sub-interfaces, classes, and subclasses are all supported.
- Offers scalable HTML5 client-side development.
- Itmakes use of data structures to the fullest. Thus providing a better web page design and organization of data.
- Supports JS libraries & API Documentation.
- It does not require a specific runtime environment to execute.
- It has a large active community developing programming language and is used by Silicon Valley corporations such as Google, Adobe, and others.
Components of TypeScript
Before starting to use TypeScript, there are a few essential components you need to know, they are:
- TypeScript compiler
- TypeScript language service
The language comprises the core concepts of the language, such as syntax, keywords, and type annotations.
The TypeScript Language Service (TLS) is a unique component that performs editor-like applications. With this feature, developers can expect typical editor operations like statement completion, signature help, code formatting and outlining, colourization, etc. the TLS also comes with optional features such as static typing and a type inference system.
How to Use TypeScript?
After installing Node.js, the next thing is installing TypeScript using NPM or Node Package Manager. Using the following command:
npm i -g TypeScript
Using the above command, it will be installed on your computer globally (we used the –g command to install TypeScript globally).
After installing it, you can start working on your code.
Let’s say you are working with an ‘index.html’ and ‘main.ts’ file on the same folder. In the HTML program, you will connect the code to ‘main.js’ and not to ‘main.ts.’ This is because browsers do not recognize TypeScript code.
After completing the program, you will compile the code. To run the TypeScript compiler, developers type the following code.
By the above code, the compiler is told to compile the code in the main.ts file and create a new file under the name main.js. If the code works right, you will see a new main.js file in the folder you have been working on.
The code should be compiled after every time you have made changes to the code. But since that is quite a tedious task, you can simply add a -w to simplify the compiling process:
tsc main.ts -w
The -w refers to watch mode, which specifies that the compiler will run in watch mode and automatically compile the code whenever the file is saved.