How to execute the TypeScript file using the command line

In this Answer, we will go through different ways of executing typescript files from the command line.

Prerequisites

Node.js

  • Check if you have Node installed locally or not with command node -v, which will display the Node version installed in your PC.
Terminal 1
Terminal
Loading...
  • If you get any error, then download and install Node here.

TypeScript

  • To execute TypeScript files, we need to install the TypeScript compiler. To check if it was successfully installed, run tsc -v. It will display the TypeScript version that is present on your PC.
Terminal 1
Terminal
Loading...
  • If it is not installed, install it with npm or any other package manager.

  • npm install -g typescript will install TypeScript globally.

Execute TypeScript file

If the mentioned prerequisites are satisfied, we are good to execute TypeScript files using the command line.

Let’s see some methods to run the above file from a terminal.

Method 1

  1. tsc filename.ts
  2. node filename.js

When we execute tsc filename.ts, TypeScript will generate a js file with the same name at runtime. To execute the generated js file, run node filename.js.

A TypeScript file with the name helloworld.ts is created with some content. You just need to run the below commands to execute helloworld.ts.

tsc helloworld.ts
node helloworld.js

Click on the “Run” button to open the terminal and then execute the given commands. You will get the output hello world from typescript file.

console.log("hello");

Method 2

We can use the ts-node package to execute TypeScript files from the command line. Click the “Run” button to open a terminal.

Install it with npm or other package manager.

  • npm install -g ts-node

After that, simply execute the TypeScript files with the command:

  • ts-node filename.ts.

To execute for the same file we tried in method 1, run:

  • ts-node helloworld.ts.

You will get the output hello world from typescript file.

console.log("hello");