前兩天我先學了 TypeScript 的基本語法與函式型別。
今天正式進入「後端應用」——把 Express 搭配 TypeScript 一起使用。
這天算是整個階段的轉折點,因為從這裡開始,我要告別 JavaScript 版本的 Express,
改寫成更安全、可維護的 TypeScript 版本 🚀
先建立一個新的資料夾:
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 的型別)建立設定檔:
npx tsc --init
打開 tsconfig.json
,修改幾個常用設定:
{
"target": "ES2020",
"module": "ESNext",
"rootDir": "./src",
"outDir": "./dist",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true
}
建立目錄與檔案:
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}`);
});
在 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 👋
既然都用 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 會馬上提醒你這個屬性可能不存在。
目前的結構很簡單,但後面幾天會越來越清楚:
ts-express-api/
├── src/
│ └── index.ts
├── tsconfig.json
├── package.json
└── node_modules/
等到 Day 25~26,我們會把這些拆成 controllers/
, dto/
, services/
等資料夾,
讓整個專案更有組織感。
今天的收穫非常實際。
原本用 JavaScript 寫 Express 已經很順了,但換成 TypeScript 後:
req
、res
的型別與屬性TypeScript 一開始確實多一些設定,但設定好後開發體驗非常順。
而且錯誤在「執行前」就能被發現,對後端 API 來說超重要。