How to Easily Set Up an Express API with TypeScript

Introduction

In this tutorial, we will see how to create a basic Express Node.js app using TypeScript. Setting up TypeScript involves several steps, and missing any step can lead to frustrating errors. So let’s begin!

Prerequisites
  • Familiarity with nodejs
Step 1:

Create A empty folder and that folder in the vs code.

Step 2:

Open terminal and type first command.

npm init -y
Enter fullscreen mode Exit fullscreen mode

this will initialize package.json file

Step 3:

Install this dependencies :

npm install express typescript ts-node @types/node @types/express nodemon
Enter fullscreen mode Exit fullscreen mode

ts-node: This is a TypeScript execution engine for Node.js. It allows you to run TypeScript directly without having to compile it to JavaScript first.

@types/node: This package provides type definitions for Node.js. It allows TypeScript to understand the types used in Node.js

nodemon: This is a utility that monitors for any changes in your source and automatically restarts your server

@types/express: This package provides type definitions for Express. It helps TypeScript understand the types used in Express

Step 4:

Genrate ts.config file

npx tsc --init
Enter fullscreen mode Exit fullscreen mode
Step 5 :

You will see outdir at line 58 in compiler options in tsconfig file outdir replace it will this :

"outDir": "./dist"
Enter fullscreen mode Exit fullscreen mode
Step 6:

Add this in your tsconfig file after the compiler options :

"include": ["src/**/*.ts"], "exclude": ["node_modules", "dist"]
Enter fullscreen mode Exit fullscreen mode
Step 7:

Add this into your package.json script section

"start": "ts-node src/index.ts", "dev": "nodemon src/index.ts"
Enter fullscreen mode Exit fullscreen mode
Step 8:

Create src folder in that folder create index.ts file and this basic express API

import express, { Request, Response } from "express"; const app = express();
const port = 3000; app.use(express.json()); app.get("/", (req: Request, res: Response) => { res.send("Hello, world!");
}); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Now run your code :

npm run start
Enter fullscreen mode Exit fullscreen mode

you will see this in your terminal: Server is running on http://localhost:3000 when you will click on this you will redirected to the browser and you will see hello world.

Ok so this was a easiest way of creating a express app in ts . if you find it useful please like and comment it will motivate me to create more such blogs.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

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

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Major increase in brute force attacks on wordpress.