iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0

昨天我們認識了 TypeScript 內建的 Utility Types,

今天就來真的「動手做」,把 TypeScript 放進 Node.js 專案,

做一個簡單的 API,感受一下有型別的後端開發有多安全。


1. 為什麼要在 Node.js 用 TypeScript?

  • 自動補全:少打字,多寫對的程式。
  • 防呆:避免傳錯參數、回傳型別不一致。
  • 更容易維護:專案越大,型別的價值越大。

2. 初始化專案

先建立資料夾並初始化:

mkdir ts-node-demo
cd ts-node-demo
npm init -y

3. 安裝 TypeScript 與型別定義

npm install typescript ts-node @types/node --save-dev
  • typescript → TypeScript 編譯器
  • ts-node → 直接執行 .ts
  • @types/node → Node.js 的型別定義

4. 建立 tsconfig.json

npx tsc --init

修改幾個重要設定:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "outDir": "./dist"
  }
}

5. 安裝 Express 與型別

npm install express
npm install @types/express --save-dev

6. 建立第一個 TypeScript API

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");
});

7. 執行專案

npx ts-node src/index.ts

開啟瀏覽器或用 Postman 測試:

  • GET http://localhost:3000/users

  • POST http://localhost:3000/usersBody:

    { "id": "u1", "name": "Alice" }
    

8. 型別的好處

  • req.body 會自動帶出 User 的屬性。
  • 如果少了 idname,編譯期就報錯。
  • API 回傳型別 Response<User[]>,保證資料格式一致。

9. 常見踩坑與解法

9.1 忘記裝 @types/express

會導致 RequestResponse 型別無法使用 → 安裝即可。

9.2 沒開 strict

TypeScript 無法做最嚴格的檢查 → 建議務必開啟。

9.3 req.body 類型為 any

解法:在 Request 裡定義第三個泛型參數,指定 body 型別。


10. 延伸任務

  1. 新增 DELETE /users/:id API,並讓 TS 確保 id 是 string。
  2. User 抽到 types.ts,在多個檔案共用。
  3. 將 API Response 包成 { data: ..., message: string },並用泛型封裝。

上一篇
Day 14|Utility Types:TS 內建的型別小工具大全
下一篇
Day 16|型別安全的環境變數管理:dotenv + zod
系列文
我與型別的 30 天約定:TypeScript 入坑實錄19
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言