Lab 12: Express TypeScript

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Express with @types/express: typed Request/Response/NextFunction, Request augmentation, typed middleware, Zod validation middleware.


Step 1: Setup

docker run -it --rm node:20-alpine sh
npm install -g typescript ts-node
mkdir /lab12 && cd /lab12
npm init -y
npm install express zod
npm install --save-dev @types/express @types/node
cat > tsconfig.json << 'EOF'
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true
  }
}
EOF

Step 2: Basic Typed Route Handlers


Step 3: Request Interface Augmentation


Step 4: Typed Middleware


Step 5: Zod Validation Middleware


Step 6: Full Express Application


Step 7: Error Handling Middleware


Step 8: Capstone — Verifiable Server Test

Run:

📸 Verified Output:


Summary

Concept
Pattern

Typed handler

(req: Request<P,B,Q>, res: Response)

Request augmentation

declare global { namespace Express { interface Request { ... } } }

Typed middleware

(req, res, next: NextFunction): void

Zod validation

schema.safeParse(req.body)

Error middleware

4 params (err, req, res, next)

Async wrapper

fn(...).catch(next)

Last updated