Menu

TypeScript with Node.js

Lesson 1: TypeScript with Node.js

What does a typed Node.js project need?

Piece Tool or setting
Node.js types npm install -D @types/node and "types": ["node"]
Run TypeScript node src/server.ts (type stripping) or tsx watch src/server.ts
Type-check tsc --noEmit with module: nodenext
Web framework types Express (@types/express), or frameworks with built-in types such as Fastify and Hono
Config validation Zod or similar, at startup

Example

// src/server.ts
import express, { type Request, type Response } from 'express';
import type { Product } from './types.ts';

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

const products: Product[] = [
  { id: 'p1', name: 'Milk 1L', price: 6400, category: 'dairy' },
  { id: 'p2', name: 'Basmati Rice 5kg', price: 64500, category: 'grains' },
];

// Request<Params, ResBody, ReqBody, Query>
app.get('/products/:id', (req: Request<{ id: string }>, res: Response<Product | { error: string }>) => {
  const product = products.find((p) => p.id === req.params.id);
  if (!product) return res.status(404).json({ error: 'Product not found' });
  res.json(product);
});

type CreateOrderBody = { items: { productId: string; quantity: number }[] };

app.post('/orders', (req: Request<{}, unknown, CreateOrderBody>, res) => {
  const { items } = req.body; // Typed, but NOT validated yet (Lesson 3)
  res.status(201).json({ id: `QC-${Date.now()}`, items });
});

app.listen(3000, () => console.log('QuickCart API on http://localhost:3000'));

How it works

  • Express's generic Request type lets you describe params, response body, request body, and query string.
  • These types are promises you make, not checks. A client can still send anything, so validate req.body at runtime (Lesson 3).
  • process.env.X is always string | undefined. Validate environment variables once at startup and export a typed env object.
// src/env.ts
const port = Number(process.env.PORT ?? 3000);
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) throw new Error('DATABASE_URL is required');

export const env = { port, databaseUrl } as const;

Common mistakes

Mistake Effect Fix
Annotating req.body and trusting it Invalid data reaches the database Validate with a schema
Using process.env.X! everywhere Crashes later with unclear errors Validate once at startup
Forgetting "types": ["node"] process, Buffer unknown Add Node types to tsconfig.json

Key takeaways

  • Type requests, responses, and config, but remember types describe, they do not validate.
  • Validate environment variables and request bodies at the edges of your app.

Try it: Add GET /products?category=dairy with a typed query parameter and a 400 response for unknown categories.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details