At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

Developing an Express Application Using TypeScript

  • By Nagaraj Ravi
  • February 25, 2020
  • 1192 Views

Hi friends, this is Nagaraj. Having 3 years of experience in MEAN stack development, developing a node js project in javascript is a common thing in MEAN stack development. We can also use javascript transpiler programming languages like typescript, and coffee-script. The javascript is a dynamic programming language. So, you can’t define a data type in source codes.
Thereby, we will face some problems while developing some complex type of project. If we use static programming for developing a project, it is good and easy to develop and manage the project.  Here, we will discuss how to develop a Node js project using Typescript. 

What is Typescript? 

Typescript is nothing but a programming language for developing javascript projects. It is a statically typed and an object-oriented programming language. So we can define a type for every single variable, and function’s return values. There are some Object Oriented Programming language features available other than ES6 oops features.  This is not an executable programming language, it’s just used to convert its source code into javascript. Thereby we can finally use the javascript code into our project. The typescript compiler is a translator type of compiler. It compiles the typescript code into javascript source codes. We can compile a single typescript file and also compile a full project by using typescript configurations.

Read More: How to make your HTML responsive with CSS

How to develop a Node js project in Typescript?

We need to configure the project source files that are needed to be converted into javascript source codes in tsconfig file. When we compile a project, it finally gets the javascript code file in the respective folder. Or we can compile all the typescript file source code into one single project.  Once the javascript code is generated, we run the javascript code using node command. I will showcase the steps in the following notes. Also, the source code available in my git repository. I have developed the Nodejs project using express js framework. This is a simple project link.

  1. Install the Node js tool by referring to this link .
  2. Install Typescript tools by using this command “npm install -g typescript ts-node ”.
  3. We need to create a project folder and then run this command “npm initnpm init ” to configure the node project.
  4. Go to the project and create typescript configuration by using ”tsc –init ” then there is a tsconfig.json file will be generated.
  5. Install express js, mongoose, nodemon package and its types.
  6. Run npm install –save @types/express express body-parser mongoose nodemon socket.io @types/socket.io”.
  7. Create a folder named “src”  inside the project. You should write all the source codes in this folder. 
  8. Configure tsconfig.json files as follows.  

 

{
 "compilerOptions": {
   "target": "es5",
   "module": "commonjs",
   "outDir": "./dist",
   "strict": true,
   "baseUrl": "./",
   "esModuleInterop": true,
   "experimentalDecorators": true,
   "emitDecoratorMetadata": true,
   "forceConsistentCasingInFileNames": true,
   "allowSyntheticDefaultImports": true,
//    "noImplicitAny": true,
   "allowJs": true,
   "lib": ["es2015"]
 },
 "includes": [
   "./src/**/*.ts"
 ],
 "exclude": [
   "node_modules"
 ]
}

       8. Configure the pacakge.json script as follows

"scripts": {
 "build": "tsc",
 "dev": "ts-node ./src/server.ts",
 "start": "nodemon ./dist/server.js",
"prod": "npm run build && npm run start"
}

       9. Now write your typescript source codes in the “src” folder or you can get the source code from the above-mentioned repo src folder. Else, create the server.ts file and copy the following code.

import express, {Request, Response} from "express";
import http from "http";
import * as bodyParser from "body-parser";
class AppServer {
   app: express.Application;
   static PORT = 3000;
   constructor() {
       this.app = express();
   }
   config() {
       this.logs();
       this.bodyParser();
       this.routes();
   }
   static start() {
       const appServer = new AppServer();
       appServer.config();
       const server = http.createServer(appServer.app);
       server.listen(AppServer.PORT);
   }
   private bodyParser() {
       this.app.use(bodyParser.json());
       this.app.use(bodyParser.urlencoded({extended: false}));
   }
   private routes() {
       this.app.get('/', async (req: Request, res: Response) => {
           res.status(200).send('<H1>HELLO WOLRD</H1>');
       });
       this.app.use('/products', ProductControllers.getRouter())
   }
   private logs() {
       this.app.use((req, res) => {
           console.log('REQUEST IS: ', req.path, new Date().toLocaleString());
       })
   }
}
class ProductControllers {
   router: express.Router;
   constructor() {
       this.router = express.Router();
   }
   static getRouter() {
       const instance = new ProductControllers();
       return instance.config();
   }
   config() {
       this.configGetProductsRoutesHandler();
       return this.router;
   }
   configGetProductsRoutesHandler() {
       this.router.get('/', async (req: Request, res: Response) => {
           res.status(200).send([{
               id: '23fd3er',
               name: 'puma'
           }]);
       })
   }
}
AppServer.start();

   10. Then run your project with this command “npm run dev ” .

Read More: An Ultimate Architecture Flow For Your Next Node.js Project

Advantages of Developing a Node JS Project in Typescript

Developing a node js project in typescript there are a lot of advantages we will see that in the following list.

  1. Typescript is a statically typed programming language. This means you can specify the types in source codes. So, you can avoid several run-time and development issues. 
  2. You can target you build source into multiple ECMAScript versions.
  3. There are some oops concepts available like interface, abstract, decorators that will help you increase your coding reusability, and support your coding style.
  4. It will help you to write in-design patterns more easily than in javascript.
  5. Dependency injection packages are available for typescript. So, it helps you to manage your object creation.

Disadvantages of Developing a NodeJS Project inTypescript

I think there is no significant disadvantage in developing Node js project in typescript. But, maybe for some packages, you may not have type declaration files or the package is only developed in javascript. 

Note:

There’s no problem if you don’t know typescript. You can write your code similar to javascript but that is not a good idea. If you don’t know typescript then learn and code it. It’s not too tough. If you are reading this blog, I am sure you are familiar with javascript, so learn typescript.
I may have missed some notes on the advantages and disadvantages.  Spread your knowledge on that to the world through comments below. 
If you have a business idea in your mind and searching for a reliable web development company, you are in the right place. Hire the best Node JS developers in the industry from Agira technologies.

Looking for a Tech partner to dominate the digital world?

Nagaraj Ravi

A zealous full stack web developer with 3 years of professional experience. Hybrid application development and in developing Open-source projects are the best of my list. Out of passion ethical hacking is one of my hobbies. Yet, I am good at analyzing Web Security. And I teach machines with my expertise in Robotics and Machine learning.