How to compile a Typescript file?

In this article are going to explore TypeScript and how to execute the same. TypeScript is an open-source programming language developed and maintained by Microsoft.

Typescript is a bit syntactically different from the native JavaScript but also adds additional features to it. Typescript is the superset of JavaScript with a strong pace of development and object-oriented programming. It also does not run directly on the web browsers as JavaScript runs

Typescript files need to be combined with JavaScript first and then they work as normal JavaScript. In order to compile and execute the typescript file, we need to install the node and then use it to compile typescript onto your local system. In this article, we are going to look at how to compile a typescript file.

Setup for Typescript

You need to follow the below steps to work with typescript files −

  • Download & Install node.js and Node Package Manager(NPM).

  • Setup the NPM Environment variables for the typescript to work.

  • You can use the below command to check the Node & NPM version installed on your system.

For Node version

node -v

For NPM version

npm -v

Note − We don’t need to explicitly install the NPM packages. Node will automatically download install NPM while downloading node.

Once the Node and NPM is installed, we need to install the Typescript on our system.

npm install -g typescript

On successfully downloading the typescript we can now use it to compile our typescript into the native JavaScript. Please note the typescript files should be in the same directory where the typescript is downloaded onto the system.

Example 1

In the below example, we have created a simple typescript file with 3 values i.e. greet, org, and tagLine. This file is in typescript. Now, we will use the below commands to compile this file into a JS file.

#Filename: index.ts

var greet : string = "Welcome to";
var org : string = "TutorialsPoint!";
var tagLine : string = "SIMPLY LEARNING!"
console.log(greet+ " "+org );

Now run the following command for compiling the typescript file into the JavaScript file.

tsc index.ts

This will automatically create a JavaScript file with the following name – index.js. The file will be created in the same folder where the typescript file is located. Now run the JS file using the below command:

node index.js

The generated JavaScript file will look like this. You can see in the below file that the NPM has compiled the Typescript file into the JavaScript file.

# index.js

var greet = "Welcome to";
var org = "TutorialsPoint!";
var tagLine = "SIMPLY LEARNING!";
console.log(greet + " " + org);


The output of the above file on execution is shown below −

Welcome to TutorialsPoint!

Updated on: 22-Apr-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started