TypeScript cho backend Node.js
Trong khóa JavaScript, bạn đã biết Node.js hiện đại chạy được file .ts trực tiếp. Bài này ghép mọi thứ lại thành một cấu trúc backend TypeScript gọn, an toàn kiểu từ request đến database.
Chọn cách chạy
| Cách | Khi nào dùng | Lưu ý |
|---|---|---|
node src/main.ts (type stripping) | Dev và production đơn giản, Node ≥ 22.18 / 23.6 | Chỉ cú pháp "erasable"; không kiểm tra kiểu |
tsx / bundler (esbuild, tsup...) | Cần cú pháp không erasable hoặc đóng gói | Thêm một công cụ |
tsc → dist/*.js → node dist/main.js | Thư viện publish lên npm, cần file .d.ts | Thêm bước build |
Dù chạy kiểu nào, kiểm tra kiểu luôn là tsc --noEmit chạy riêng (editor, CI, pre-commit).
tsconfig cho Node chạy .ts trực tiếp
{
"compilerOptions": {
"target": "es2024",
"module": "nodenext",
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"noUncheckedIndexedAccess": true,
"types": ["node"]
},
"include": ["src"]
}allowImportingTsExtensions: cho phépimport { db } from "./db.ts"— Node cần đuôi file thật.erasableSyntaxOnly(TS 5.8): báo lỗi nếu bạn dùngenum,namespace, parameter property — những thứ Node không chạy được bằng type stripping.verbatimModuleSyntax: buộc viếtimport typecho import chỉ dùng kiểu, để công cụ xóa kiểu không phải đoán.
NOTE
Nếu cần build ra .js, thay noEmit bằng outDir và bật rewriteRelativeImportExtensions (TS 5.7) để ./db.ts được đổi thành ./db.js khi emit.
Cấu trúc theo lớp, kiểu chảy một chiều
- Biên vào: body, query, params, header là
unknowncho đến khi qua schema (chương 10). - Service nhận input đã có kiểu, trả
Resultcho lỗi nghiệp vụ. - Repository: dùng ORM/query builder sinh kiểu từ schema DB (Prisma, Drizzle, Kysely...) thay vì tự viết
interfacelặp lại bảng. - Biên ra: map entity sang DTO — đừng trả nguyên object DB (lộ
passwordHash!).
import type { Request, Response } from "express";
import { CreateOrderInput } from "./schema.ts";
import { createOrder } from "./service.ts";
export async function postOrder(req: Request, res: Response) {
const parsed = CreateOrderInput.safeParse(req.body); // req.body: any → kiểm tra ngay
if (!parsed.success) return res.status(400).json({ error: "Dữ liệu không hợp lệ" });
const result = await createOrder(parsed.data);
if (!result.ok) {
const status = result.error.kind === "out_of_stock" ? 409 : 422;
return res.status(status).json({ error: result.error });
}
return res.status(201).json(toOrderDto(result.value));
}Mở rộng kiểu của thư viện
Muốn gắn req.user sau middleware xác thực? Dùng module augmentation (chương 9) thay vì (req as any).user:
import "express";
declare module "express" {
interface Request {
user?: { id: string; role: "admin" | "member" };
}
}Cấu hình và biến môi trường
Parse process.env một lần lúc khởi động; thiếu biến thì dừng ngay, đừng để lỗi nổ lúc 3 giờ sáng:
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Thiếu biến môi trường ${name}`);
return value;
}
export const config = {
port: Number(process.env.PORT ?? 3000),
databaseUrl: required("DATABASE_URL"),
jwtSecret: required("JWT_SECRET"),
} as const;Chia sẻ kiểu với frontend
Trong monorepo, đặt schema và DTO vào một package chung (packages/contracts) để frontend và backend import cùng một nguồn. Đổi một trường ở API → frontend báo lỗi compile ngay, thay vì hỏng trên production.
TIP
Cùng một quy tắc xuyên suốt: kiểm tra ở biên, tin tưởng ở lõi, ánh xạ khi trả ra.
Comments