How to Create a TypeScript Project with ExpressJS the Simplest Way!! By SilvenLEAF

If you are wondering how to create a TypeScript BackEND project, fear not my brave knight. It's way easier than you can ever imagine!! Let go!

Step 1

First init our project by running npm init -y on our terminal, it'll create a package.json file. Then let's install these packages by running the following command on our terminal

npm i typescript ts-node express @types/node @types/express

typescript is the core package for typescript, ts-node is the typescript version of node for runnig .ts files just as we do with node app.js, in this case we do, ts-node app.ts. @types/node and @types/express has all the types for node and express respectively. You say why? Well typescript is all about type na :)

Bonus Step

Now let's install some helping dev stuff

npm i --D nodemon ts-node-dev

ts-node-dev package binds nodemon with typescript. The typescript version for nodemon app.js is ts-node-dev app.ts

Now let's update our package.json file

....keep others unchanged
  "main": "app.ts",
  "scripts": {
    "start": "ts-node app.ts",
    "dev": "ts-node-dev app.ts"
  },
  ...keep others unchanged

Step 2

Run the following command, it'll will create a tsconfig.json file.

tsc --init

Step 3

Let's create an express App
Write these on the app.ts file that we created

import express, { Request, Response } from 'express';
import path from 'path';




// -------------------firing express app
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname, 'client/build')));




// -------------------routes
app.get('/home', (request: Request, response: Response)=>{
  console.log(request.url)
  response.json({ message: `Welcome to the home page!` })
});



// --------------------Listen
const PORT = process.env.PORT || 5000;
app.listen(PORT, ()=>{
  console.log(`Server running on PORT ${ PORT }`);
})

Yippie, our very first typescript express app is ready. Let's run and test it

Type either npm start or npm run dev and then go to the localhost:5000/home and test it out yourself. Enjoy!

25