Node.js with TypeScript: Project Setup and Best Practices

TypeScript makes Node.js development much more pleasant. Types catch bugs early and improve editor support. Here’s how to set up a TypeScript Node project properly.

Project Setup

mkdir my-node-app && cd my-node-app
npm init -y
npm install typescript ts-node @types/node -D
npx tsc --init

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2019",
    "module": "commonjs",
    "lib": ["ES2019"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Package Scripts

{
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "ts-node src/index.ts",
    "watch": "tsc --watch"
  }
}

Basic Express App

// src/index.ts
import express, { Request, Response } from 'express';

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

interface User {
  id: number;
  name: string;
  email: string;
}

const users: User[] = [];

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

app.post('/users', (req: Request<{}, {}, User>, res: Response) => {
  const user = { id: Date.now(), ...req.body };
  users.push(user);
  res.status(201).json(user);
});

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

Development Tools

# Auto-restart on changes
npm install nodemon -D

# Add to package.json scripts
"dev": "nodemon --exec ts-node src/index.ts"

Best Practices

  • Enable strict mode from day one
  • Install @types packages for libraries
  • Use interfaces for request/response shapes
  • Keep src and dist separate

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.