Ts Nodejs
TypeScript is widely used in Node.js backend development. This tutorial introduces the TypeScript configuration and usage for Node.js projects.
Using TypeScript makes Node.js code safer and easier to maintain, making it especially suitable for medium to large backend projects.
> Node.js tutorial: [
* * *
* * *
## Why Use TypeScript in Node.js
Node.js projects typically involve complex business logic and data processing, and the lines of code can grow rapidly.
Using TypeScript can: provide compile-time type checking to reduce runtime errors; leverage IDE intelligent hints 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.
> **Advantage:** TypeScript's static type checking can catch 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.js type definitions
# -D means install as a development dependency
npm install -D typescript @types/node ts-node nodemon
# Initialize tsconfig.json
npx tsc --init
> **Note:** `@types/node` provides type definitions for the Node.js API, `ts-node` can run TypeScript files directly, and `nodemon` monitors 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":,
// Output directory
"outDir":"./dist",
// Source root directory
"rootDir":"./src",
// Strict mode (always enable)
"strict":true,
// ES module interoperability
"esModuleInterop":true,
// Skip library check
"skipLibCheck":true,
// Force consistent file name casing
"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:** Node.js projects recommend using `module: "commonjs"`, which is the module system natively supported by Node.js.
* * *
## Define 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{
success:boolean;// Whether successful
data?: T;// Data on success
error?: string;// Error message on failure
}
> **Type Definitions:** Centralizing type definitions in the types directory makes them easier to maintain and reuse.
* * *
## Implement 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{
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{
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{
return{ success:true, data:this.users};
}
}
// Export singleton
export default new UserService();
**Run Result:**
UserService instantiated successfully
> **Service Layer:** Business logic is centralized in the service layer, making it easier to test and reuse.
* * *
## Create API Routes
Use the Express framework to create a RESTful API.
## src/index.ts
import express,{ Request, Response } from "express";
import userService from "./services/userService";
// Create Express application
const app = express();
// Parse JSON request body
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}`);
});
**Run Result:**
Server running at http://localhost:3000
> **Type Hints:** Using `Request` and `Response` types, the IDE will provide complete property hints.
* * *
## 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 monitor changes and automatically restart
"dev":"nodemon --exec ts-node src/index.ts",
// Run tests
"test":"jest"
}
}
> **Development Efficiency:** Using `npm run dev` allows the server to automatically restart after code modifications.
* * *
## Notes
* **Strict Mode:** Always enable strict: true
* **Module Selection:** Use commonjs for Node.js projects
* **Type Definitions:** Install @types/node to get API types
* **Development Tools:** Use ts-node for hot reloading
> **Best Practices:** Keep type definitions and business logic separated 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:** Centralize interface management in the types directory
* **Service Layer:** Separate business logic from routes
* **Routes:** Use Express to create RESTful APIs
* **Development Tools:** ts-node, nodemon improve development efficiency
> **Suggestion:** Use TypeScript directly for new projects; older projects can be migrated gradually.
YouTip