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.
| 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).
.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ép import { 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ùng enum, namespace, parameter property — những thứ Node không chạy được bằng type stripping.verbatimModuleSyntax: buộc viết import type cho 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.
unknown cho đến khi qua schema (chương 10).Result cho lỗi nghiệp vụ.interface lặp lại bảng.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 =
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" };
}
}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 =
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