TypeScript + Node.js Practical Guide

TypeScript is widely used in Node.js backend development. This tutorial covers the TypeScript configuration and usage for Node.js projects.

Using TypeScript makes Node.js code safer and easier to maintain, especially suitable for medium to large backend projects.

Node.js Tutorial: Viewhttps://www.example.com/nodejs/nodejs-tutorial.html


SVG Diagram: Node.js + TypeScript Project Structure Background Title Node.js + TypeScript Project Structure Project Configuration Project Configuration package.json tsconfig.json ts-node Source Code Source Code (src/) types/ - Type definitions services/ - Business logic routes/ - Route handling Compiled Output Compiled Output (dist/) .js - JavaScript .d.ts - Type declarations .map - Source maps Runtime Node.js Runtime Execute JS Bottom half: Development workflow Development Workflow Step 1 npm install dependencies Step 2 tsc compiles TypeScript Step 3 node runs JavaScript Step 4 API request testing Arrow marker

Why Use TypeScript in Node.js

Node.js projects often involve complex business logic and data processing, and the codebase can grow rapidly.

Using TypeScript can: provide compile-time type checking to reduce runtime errors; leverage IDE smart suggestions to improve development efficiency; make code easier to read and maintain.

Many large Node.js projects (such as NestJS) recommend or use TypeScript by default.

Advantages:TypeScript's static type checking can detect potential issues during development, which is more efficient than runtime debugging.


Project Initialization

First, initialize the Node.js project and install TypeScript-related dependencies.

Initialize Project

# Initialize npm
npm init -y

# Install TypeScript and Node.jsType Definitions
# -D means installing as a dev dependency
npm install -D typescript @types/node ts-node nodemon

# Initialize tsconfig.json
npx tsc --init

Notes:@types/nodeProvides type definitions for Node.js APIs,ts-nodeCan run TypeScript files directly,nodemonWatches for file changes and automatically restarts.


tsconfig.json Configuration

Configure TypeScript compiler options, optimized for Node.js projects.

tsconfig.json

{
    "compilerOptions": {
        // Compilation target: ES2020
        "target": "ES2020",

        // Module system: CommonJS (natively supported by Node.js)
        "module": "commonjs",

        // Enabled libraries
        "lib": ["ES2020"],

        // Output directory
        "outDir": "./dist",

        // Source root directory
        "rootDir": "./src",

        // Strict mode (always enabled)
        "strict": true,

        // ES module interop
        "esModuleInterop": true,

        // Skip library checks
        "skipLibCheck": true,

        // Enforce consistent casing in file names
        "forceConsistentCasingInFileNames": true,

        // Module resolution strategy
        "moduleResolution": "node",

        // Generate declaration files
        "declaration": true
    },
    // Files to compile
    "include": ["src/**/*"],
    // Excluded files
    "exclude": ["node_modules", "dist"]
}

Recommended configuration:Recommended for Node.js projects to usemodule: "commonjs", which is the module system natively supported by Node.js.


Defining Types

Define the project's type interfaces in the types directory.

src/types/index.ts

// User type definition
export interface User {
    id: number;         // User ID
    name: string;       // Username
    email: string;      // Email
    createdAt: Date;   // Creation time
}

// Data transfer object for creating a user
export interface CreateUserDTO {
    name: string;       // Username (required)
    email: string;     // Email (required)
    password: string;   // Password (required)
}

// API response type (generic)
export interface ApiResponse<T> {
    success: boolean;   // Whether successful
    data?: T;         // Data on success
    error?: string;   // Error message on failure
}

Type definitions:Centralize type definitions in the types directory for easier maintenance and reuse.


Implementing Services

Implement business logic in the services directory, using the defined types.

src/services/userService.ts

// Import type definitions
import { User, CreateUserDTO, ApiResponse } from "../types";

// User service class
class UserService {
    // User list (in-memory storage)
    private users: User[] = [];
    // Next user ID
    private nextId = 1;

    // Create user
    createUser(dto: CreateUserDTO): ApiResponse<User> {
        try {
            // Create user object
            const user: User = {
                id: this.nextId++,
                name: dto.name,
                email: dto.email,
                createdAt: new Date()
            };
            this.users.push(user);
            return { success: true, data: user };
        } catch (error) {
            return { success: false, error: "Failed to create user" };
        }
    }

    // Get a single user
    getUser(id: number): ApiResponse<User> {
        const user = this.users.find(u => u.id === id);
        if (!user) {
            return { success: false, error: "User not found" };
        }
        return { success: true, data: user };
    }

    // Get all users
    getAllUsers(): ApiResponse<User[]> {
        return { success: true, data: this.users };
    }
}

// Export singleton
export default new UserService();

Execution result:

UserService 实例化成功

Service layer:Business logic is centralized in the service layer for easier testing and reuse.


Creating API Routes

Create RESTful APIs using the Express framework.

src/index.ts

import express, { Request, Response } from "express";
import userService from "./services/userService";

// Create Express app
const app = express();
// Parse JSON request bodies
app.use(express.json());

// Get all users
app.get("/api/users", (req: Request, res: Response) => {
    const result = userService.getAllUsers();
    res.json(result);
});

// Get a single user
app.get("/api/users/:id", (req: Request, res: Response) => {
    const id = parseInt(req.params.id);
    const result = userService.getUser(id);
    res.json(result);
});

// Create user
app.post("/api/users", (req: Request, res: Response) => {
    const result = userService.createUser(req.body);
    res.json(result);
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

Execution result:

服务器运行在 http://localhost:3000

Type hints:UsingRequestandResponsetype, the IDE will provide full property suggestions.


package.json Scripts

Configure npm scripts to simplify the development workflow.

package.json

{
    "scripts": {
        // Compile TypeScript
        "build": "tsc",

        // Run compiled JavaScript
        "start": "node dist/index.js",

        // Development mode: use nodemon to watch for changes and auto-restart
        "dev": "nodemon --exec ts-node src/index.ts",

        // Run tests
        "test": "jest"
    }
}

Development efficiency:Usingnpm run devallows automatic server restart after code changes.


Notes

  • Strict mode:Always enable strict: true
  • Module selection:Node.js projects should use commonjs
  • Type definitions:Install @types/node to get API types
  • Development tools:Use ts-node for hot reloading

Best practices:Keep type definitions separate from business logic for easier testing and maintenance.


Summary

TypeScript is an excellent choice for Node.js backend development.

  • Project configuration:Use tsconfig.json to configure compilation options
  • Type definitions:Centrally manage interfaces in the types directory
  • Service layer:Separate business logic from routes
  • Routes:Use Express to create RESTful APIs
  • Development tools:ts-node and nodemon improve development efficiency

Recommendation:Use TypeScript directly for new projects; existing projects can be migrated gradually.

Other Extensions