codez.guru

Setting Up TypeScript in a Node Project

npm init -y
npm install typescript ts-node-dev --save-dev
npx tsc --init

Enable these options in tsconfig.json:

"esModuleInterop": true,
"strict": true,
"rootDir": "src",
"outDir": "dist"

Installing Express with Type Support

npm install express
npm install --save-dev @types/express

Create a folder called src/ and add your server file there.


Creating a Basic Express Server

// src/index.ts
import express from "express";

const app = express();
app.use(express.json());

app.get("/", (req, res) => {
  res.send("Hello from TypeScript + Express!");
});

app.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});

Run with:

npx ts-node-dev src/index.ts

Typing Request and Response Objects

You can add types from Express:

import { Request, Response } from "express";

app.get("/user", (req: Request, res: Response) => {
  res.json({ name: "Lior" });
});

Defining Request Body and Params Types

Type your API like you would a function:

type User = {
  name: string;
  age: number;
};

app.post("/users", (req: Request<{}, {}, User>, res: Response) => {
  const user = req.body; // Fully typed
  res.status(201).json(user);
});

You can also type req.params and req.query:

app.get("/user/:id", (req: Request<{ id: string }>, res: Response) => {
  const { id } = req.params;
  res.send(`User ID: ${id}`);
});

Summary

  • TypeScript + Express = fast and safe backend APIs
  • Use ts-node-dev for live-reloading
  • Use generics in Request<params resbody reqbody> for full typing
  • Clean up logic with interfaces, validation, and middleware

Next up: Lesson 18 – Defining API Schemas with Zod and TypeScript