iT邦幫忙

2025 iThome 鐵人賽

DAY 21
0
自我挑戰組

《轉職學習日記:JavaScript × Node.js × TypeScript × Docker × AWS ECS》系列 第 21

Day21 - 持續成長學習藍圖 - TypeScript(Express )

  • 分享至 

  • xImage
  •  

前兩天我先學了 TypeScript 的基本語法與函式型別。
今天正式進入「後端應用」——把 Express 搭配 TypeScript 一起使用。

這天算是整個階段的轉折點,因為從這裡開始,我要告別 JavaScript 版本的 Express,
改寫成更安全、可維護的 TypeScript 版本 🚀


1. 建立專案與初始化

先建立一個新的資料夾:

mkdir ts-express-api
cd ts-express-api
npm init -y

接著安裝所需套件:

npm install express
npm install --save-dev typescript ts-node-dev @types/node @types/express

說明:

  • typescript:TypeScript 編譯器
  • ts-node-dev:像 nodemon 一樣,可以即時編譯 & 重啟
  • @types/node@types/express:型別定義檔(讓 TS 知道 Node 與 Express 的型別)

2. 初始化 TypeScript

建立設定檔:

npx tsc --init

打開 tsconfig.json,修改幾個常用設定:

{
  "target": "ES2020",
  "module": "ESNext",
  "rootDir": "./src",
  "outDir": "./dist",
  "moduleResolution": "node",
  "esModuleInterop": true,
  "strict": true
}

3. 建立第一支 TypeScript 版 Express

建立目錄與檔案:

src/
 └── index.ts

內容如下:

import express, { Request, Response } from "express";

const app = express();
const port = 3000;

app.get("/", (req: Request, res: Response) => {
  res.send("Hello TypeScript + Express 👋");
});

app.listen(port, () => {
  console.log(`🚀 Server is running at http://localhost:${port}`);
});

4. 啟動伺服器

package.json 裡加上 script:

"scripts": {
  "dev": "ts-node-dev --respawn --transpile-only src/index.ts"
}

然後執行:

npm run dev

看到以下輸出就成功了 👇

🚀 Server is running at http://localhost:3000

打開瀏覽器輸入 http://localhost:3000
就能看到訊息:

Hello TypeScript + Express 👋


5. 加上型別與 Middleware

既然都用 TypeScript,順便來練習在 Express 裡加上型別定義:

app.use(express.json());

app.post("/hello", (req: Request, res: Response) => {
  const name: string = req.body.name;
  res.json({ message: `你好,${name}!` });
});

如果忘記傳 name,TypeScript 會馬上提醒你這個屬性可能不存在。


6. 檔案結構

目前的結構很簡單,但後面幾天會越來越清楚:

ts-express-api/
├── src/
│   └── index.ts
├── tsconfig.json
├── package.json
└── node_modules/

等到 Day 25~26,我們會把這些拆成 controllers/, dto/, services/ 等資料夾,
讓整個專案更有組織感。


🎯 學習心得 / 今日收穫

今天的收穫非常實際。
原本用 JavaScript 寫 Express 已經很順了,但換成 TypeScript 後:

  • 編輯器能即時提示 reqres 的型別與屬性
  • 函式輸入/輸出都有型別保護
  • 跑起來幾乎沒什麼額外負擔

TypeScript 一開始確實多一些設定,但設定好後開發體驗非常順。
而且錯誤在「執行前」就能被發現,對後端 API 來說超重要。


上一篇
Day20 - 持續成長學習藍圖 - TypeScript(Enum 與函式型別)
系列文
《轉職學習日記:JavaScript × Node.js × TypeScript × Docker × AWS ECS》21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言