Home

How to run your TypeScript code

You need a TypeScript compiler to compile your TypeScript code into JavaScript code, so that you can execute it. So we begin with installing some packages for that purpose.

npm install --global typescript ts-node

If you are on MacOS you might need to add 'sudo' in front of the above command. Otherwise you may get a 'EACCESS' error.

A sample TypeScript app

The following TypeScript code will fetch a todo from a API:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

The above code is valid JavaScript code, but it is also a valid TypeScript code.

Compiling and Running the TypeScript code

To compile the above index.ts file. You need to use tsc:

tsc index.ts

After running the above command you can see a new index.js file create inside your folder. Now you can run that JavaScript code inside index.js normally as you do with any JS code.

node index.js

You can get more info about the typescript package, using the command tsc --help

Better way

There is a faster way you can compile and run your typescript code. This is why we have installed ts-node package.

You can run the following command to compile your TypeScript code to JavaScript code and run the JavaScript code with this single line:

ts-node index.ts


Last Updated on

Next Post: Rules vs Guidelines →

Comments