Download or clone source code from here

In this blog post, you are going to learn to configure the Node.js application to use TypeScript. At the end of the blog post, you will have a REST API created using TypeScript and Express in Node.js.

Before starting to make sure that you have NodeJS installed on your machine from here. You can check whether Node.js is installed by running the command,

node –version

To start with creating a folder and change directory to that folder. In the directory create package.json file using the command:

npm init

Just keep pressing the return key (Enter) for all the questions to create a default package.json file. After that Install all dependencies for TypeScript and Express

npm install -D typescript

npm install -D tslint

npm install express -S

npm install @types/express -D

In the npm command -D flag is for –save-dev and -S flag is for –save. After successfully installing the dependencies, create a tsconfig.json file in the root of the project directory. Inside the tsconfig.json file put the following information,

{ "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "target": "es6", "moduleResolution": "node", "sourceMap": true, "outDir": "dist" }, "lib": ["es2015"] }

We have set various compiler options such that TypeScript code should be transpile to the ES6 standard of JavaScript and it should follow node.js module resolution. You can learn more about various options here

After configuring TypeScript compiler options, add a file with name tslint.json in the root folder and add this code,

{ "defaultSeverity": "error", "extends": [ "tslint:recommended" ], "jsRules": {}, "rules": { "no-console":false }, "rulesDirectory": [] }

We have enabled console in the rules for better debugging. After this, modify the package.json file. Just modify the main section and start the script as shown below.

{ "name": "typescriptinnode", "version": "1.0.0", "description": "", "main": "dist/app.js", "scripts": { "start": "tsc && node dist/app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Dhananjay Kumar <debugmode@outlook.com> (https://debugmode.net)", "license": "ISC", "devDependencies": { "@types/express": "^4.17.2", "tslint": "^5.20.1", "typescript": "^3.7.4" }, "dependencies": { "express": "^4.17.1" } }

In the package.json file main entry specifies the entry point of the application. TypeScript trasnpiles the *.ts file and put them inside dist folder with extension *.js, as we have specified that in previous steps. So, the app.ts file would be trasnpiled as an app.js file and would be saved in the dist folder.

The start entry in the script section specifies that the first TypeScript compiler will run and then the node will run the app.js file from the dist folder. In this configuration, the app.ts file is going to be the main file. If you want to make index.js as the main entry of application, modify the main and start entry in package.json file accordingly.

As of now, we have configured the Node.js project to work with TypeScript and Express. Next, create an src folder and add two files inside that app and product ts files.

After adding these two files, your project structure should look like below,

To test whether you have performed all steps correctly, in the app.ts file put the below code,

class Product { public Title ; } let p = new Product(); p.Title = "Pen"; console.log(p);

On then run the command npm start, you should get p object printed. Alright, next to create REST API using Express, in the product.ts file add below code,

export class Product { public Id : string; public Title : string; public Price : number; public inStock : boolean; }

After that in the app.ts file, put the below code:

import express from 'express'; import {Product } from './product'; const app = express(); const port = 3000; function getProduct(){ let p = new Product(); p.Id = "1"; p.Price= 100; p.Title="Cricket Bat"; p.inStock = true; return p; } app.get('/products', (req, res) => { res.send(getProduct()); }); app.listen(port, err => { if (err) { return console.error(err); } return console.log(`server is listening on ${port}`); });

Let us walk through the code,

Importing Express and product module. Due to TypeScript, we can use ES6 module export import instead of Node.js require getProducts() function returns list of products express get() method get executed when client will perform HTTP request operations on /products url. Listening to the express server at port 3000.

Now run the application again with npm start, you should get console message that server is listening on 3000. Navigate to localhost:3000/products, and you should able to get list of products returned.

Download or clone source code from here

So, you have successfully created a Node.js application using TypeScript. In another blog post, I will discuss in detail about express and TypeScript. I hope you find this post useful. Thanks for reading.