How to use Typescript with Node.js | Building a Node.js App with TypeScript

If you are using Javascript to build your application it's fine if that is a small application but once your application becomes big, it's really hard to manage the code quality.

To write the manageable and typed Javascript we started using Typescript. Typescript is just the superset of Javascript which is strictly typed.

The issue with Typescript is, it can't simply run on the browser or V8 engine. We need to transpile the Typescript to Javascript. Here in this article, we are going to use TSC to transpile the Typescript to Javascript.

Using Typescript with Node.js is super easy and I'll show you this by an example.

Let's create a file with the name package.json.

I have installed 2 dependencies @types/node and typescript.

  1. @types/node: This package contains type definitions for Node.js
  2. typescript: This package for getting the support of tsc compiler.

We will run the project through the command npm run server, which I have added in scripts array. It first transpiles the code and copies the Javascript code to dist folder and then run dist/index.js.

You just create the package.json then copy the above to that file and run command npm i. This will install all the dependencies.

To create the typescript config create a file tsconfig.json

Here we defined that it will transpile all the .ts extension files except node_modules folders file and copies the transpile files to dist folder.

Now create a file index.ts which will be transpile to index.js and will be running as the main file.

Let's create app.ts  which has been used in index.ts. app.ts has been used to create the node server.


It's all done. You were just needed to create the typescript implementation with node.js.

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *