Open In App

How to use express in typescript ?

In this article, we will see how to use Express in TypeScript. The TypeScript is a superset of JavaScript that provides type notation with the JavaScript, so we can handle our server, and very scalable for the future. Express is web framework helps to create server-side handling with the help of Nodejs

Prerequisite:



Steps to create an Express server in Typescript:

Step 1: Initiate the package.json file with your working folder with the following command.



npm init -y

Note: The ‘-y’ flag is used to make the default configuration.

After creating package.json file, the following will be the output.

Step 2: Install the required modules using the following command.

npm install express
npm i typescript ts-node nodemon --save-dev

Note: The ‘–save-dev’ is used to add dev dependency.

npm i @types/node @types/express

Step 3: Create a tsconfig.json file with the below code.

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "rootDir": "./",
    "outDir": "./build",
    "esModuleInterop": true,
    "strict": true
  }
}

Step 4: Make the following change in the package.json file to run typescript directly.

Step 5: Create an index.ts file with the following code. Here we have created a minimal express server in typescript. Here, file name is index.ts.




// Import the express in typescript file
import express from 'express';
 
// Initialize the express engine
const app: express.Application = express();
 
// Take a port 3000 for running server.
const port: number = 3000;
 
// Handling '/' Request
app.get('/', (_req, _res) => {
    _res.send("TypeScript With Express");
});
 
// Server setup
app.listen(port, () => {
    console.log(`TypeScript with Express
         http://localhost:${port}/`);
});

Step 6: Start the server using the below command.

npm start

Output: We will see the following output on the terminal screen.

Step 7: Open the browser and go to http://localhost:3000, we will see the following output.
 

Reference:

Article Tags :