How to Easily Set Up an Express API with TypeScript

RMAG news

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

this will initialize package.json file

Step 3:

Install this dependencies :

npm install express typescript ts-node @types/node @types/express nodemon

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

Step 5 :

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

“outDir”: “./dist”

Step 6:

Add this in your tsconfig file after the compiler options :

“include”: [“src/**/*.ts”],
“exclude”: [“node_modules”, “dist”]

Step 7:

Add this into your package.json script section

“start”: “ts-node src/index.ts”,
“dev”: “nodemon src/index.ts”

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}`);
});

Now run your code :

npm run start

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.

Please follow and like us:
Pin Share