Setup

Let’s return a list of products from our API. We’ll use a TypeScript interface to define the shape of a product.

Add this to index.ts above the existing GET route:

// src/index.ts

interface Product {
  id: number;
  name: string;
  price: number;
}

const products: Product[] = [
  { id: 1, name: "Laptop", price: 1200 },
  { id: 2, name: "Headphones", price: 150 },
  { id: 3, name: "Keyboard", price: 80 },
];

Add this below the existing GET route:

// GET /products
app.get("/products", (req, res) => {
  res.json(products);
});
  • The Product interface defines the structure of each product.
  • The products array contains some example products.
  • The /products route returns the array as JSON.

Now, if you visit http://localhost:3000/products, you’ll see the list of products in JSON format.



Repo link

Adding Types to req and res

You can add explicit types to the req and res parameters using Express’s built-in types:

import express, { Request, Response } from "express";

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

However, we won’t use this approach in this course because:

  • TypeScript already knows what req and res are from Express’s type definitions
  • Explicit typing adds visual noise to code examples
  • Since you’re learning API development concepts, we want to keep examples clean and focused
  • The simpler (req, res) syntax lets you focus on the actual logic

Throughout this course, we’ll use the cleaner approach and let TypeScript infer these types automatically.



Tags: