Installing TypeScript is as simple as running the following command in our Terminal:
npm i -D typescript
The above command installs TypeScript as a dev dependency in our project. We can also install it globally using:
npm i -g typescript
There are many reasons why we should use TypeScript but the most important ones are:
- TypeScript is more reliable
- TypeScript is more explicit
- Easier to refactor code without breaking it significantly.
How to use
Once we have TypeScript installed, we can start writing TypeScript files which have the extension
// File: helloWorld.ts const greeting = 'Hello world!';
What TypeScript allows us to do is we can add type definition to our code which then checked to insure we have type safety in our code.
// File: helloWorld.ts const greeting: string = 'Hello world!'; const year: number = 2021;
Our typescript page also gave us access to a TypeScript compiler. If you installed it locally, we can access it as
It will generate a
helloWorld.js file in our project. Here's what this new file contains:
// File: helloWorld.js const greeting = 'Hello world!'; const year = 2021;
We can also pass some options to our
tsc command or alternatively create a
tsconfig.json file in our project. You can learn more about the options here in official documentation.