昨天我們認識了 TypeScript 內建的 Utility Types,
今天就來真的「動手做」,把 TypeScript 放進 Node.js 專案,
做一個簡單的 API,感受一下有型別的後端開發有多安全。
先建立資料夾並初始化:
mkdir ts-node-demo
cd ts-node-demo
npm init -y
npm install typescript ts-node @types/node --save-dev
typescript
→ TypeScript 編譯器ts-node
→ 直接執行 .ts
檔@types/node
→ Node.js 的型別定義tsconfig.json
npx tsc --init
修改幾個重要設定:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist"
}
}
npm install express
npm install @types/express --save-dev
src/index.ts
:
import express, { Request, Response } from "express";
const app = express();
app.use(express.json());
type User = {
id: string;
name: string;
};
const users: User[] = [];
app.get("/users", (req: Request, res: Response<User[]>) => {
res.json(users);
});
app.post("/users", (req: Request<{}, {}, User>, res: Response<User>) => {
const newUser = req.body;
users.push(newUser);
res.status(201).json(newUser);
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
npx ts-node src/index.ts
開啟瀏覽器或用 Postman 測試:
GET http://localhost:3000/users
POST http://localhost:3000/users
Body:
{ "id": "u1", "name": "Alice" }
req.body
會自動帶出 User
的屬性。id
或 name
,編譯期就報錯。Response<User[]>
,保證資料格式一致。@types/express
會導致 Request
、Response
型別無法使用 → 安裝即可。
strict
TypeScript 無法做最嚴格的檢查 → 建議務必開啟。
any
解法:在 Request
裡定義第三個泛型參數,指定 body 型別。
DELETE /users/:id
API,並讓 TS 確保 id
是 string。User
抽到 types.ts
,在多個檔案共用。{ data: ..., message: string }
,並用泛型封裝。