How to compile and run a TypeScript program

How to run a TypeScript program:

TypeScript is a strongly typed language. It is built on JavaScript and it adds static typing to JavaScript. TypeScript helps to catch errors before the program runs. The TypeScript code is transpiled into JavaScript. So, we can run this code in any JavaScript environment.

In this post, we will learn how to run a TypeScript program. We will learn how to convert a typescript file to javascript and how to run that file. We will also learn how it behaves if it faces any errors.

1. Install the TypeScript compiler:

We will need one compiler to convert the TypeScript file to JavaScript. This is known as the typescript compiler or tsc. It will convert the TypeScript file to JavaScript and also it will throw errors if it finds any.

The TypeScript compiler can be installed globally or we can use it from a local node_modules package.

Use the below command to save it globally in your system:

npm install -g typescript

Or,

npm i -g typescript

Open a terminal, write any one of these commands, and hit enter. It will install the TypeScript compiler globally.

2. Verify the installation of the TypeScript compiler:

To verify the installation of the TypeScript compiler, you can open a terminal, type tsc, and hit enter. It will show you different available options for this compiler.

TypeScript example to run a program

It will show the compiler version, common commands, command line flags etc.

3. Compile the TypeScript program to create the JavaScript code:

If the compiler is installed, we can move to the next step, i.e. compile the program to create the JavaScript file.

Create one TypeScript file example.ts and add the below code to it:

function printMessage(msg: string) {
  console.log(msg);
}

printMessage("Hello World");

It is a simple program. The printMessage function takes one string as its parameter and logs that value on console. This function is called with the string “Hello World”.

To run this program, we will have to convert it to a JavaScript file. To do that, open a terminal, go to the folder containing this file and run the below command:

tsc example.ts

If everything goes fine, it will create one JavaScript file in that same folder, example.js.

If you open the file, it will hold the JavaScript code.

function printMessage(msg) {
    console.log(msg);
}
printMessage("Hello World");

You can now run this file with node.

node example.js

It will print the output, ‘Hello World’ on the console.

Short form:

You can also run both of these commands serially:

tsc example.ts && node example.js

It will give the same result.

You might also like: