TYPESCRIPT CORE · 95
Tooling、Build、Source Map、Runtime Validation:從 .ts 到 Production
最後一課把前面的型別知識放回工程流程。你要能判斷:錯誤來自 editor/type checker、bundler、JavaScript runtime,還是 external data。
Learning outcomes
- 能描述
.ts → check/build → .js → deploy → runtime。 - 能解釋
strict、target 與 source map 的角色。 - 能根據 evidence 分辨 type-check/build/runtime/data failure。
- 能說明 TypeScript 對 production safety 的能力邊界。
1. Toolchain pipeline
src/*.ts→ tsc / bundler →diagnostics + JS→ deploy →Browser / Node→ external API
2. tsconfig:定義 type checker / emitter 的規則
{
"compilerOptions": {
"strict": true,
"target": "ES2022",
"module": "ESNext",
"sourceMap": true
}
}
| 設定 | 概念 |
|---|---|
strict | 開啟一組較嚴格的型別檢查 |
target | 輸出 JavaScript 要對應的語言版本層級 |
module | module emit / resolution 相關策略的一部分 |
sourceMap | 讓 runtime stack trace 能對回原始 TS source |
3. Source map:production 跑的是 JS,但你想 debug TS
Build 後的 JavaScript 行號可能和 TypeScript source 不同。source map 提供映射,讓 DevTools / error reporting 能把 runtime stack 對回原始檔。
4. 四種 failure layer
| Failure | Evidence | 例子 |
|---|---|---|
| Type check | tsc diagnostic | number 傳給 string-only function |
| Build | bundler/module resolution error | import path 找不到 |
| Runtime | Browser/Node stack trace | null property access |
| External data | network payload + validation fail | API 回錯誤 shape |
5. Project checkpoint:Typed Course API Client v5
最終架構:
types.ts
Course
Result<T>
CourseState
validators.ts
isCourse()
isCourseArray()
api.ts
requestJson<T>()
app.ts
state
refreshCourse()
render()
unknown network datavalidatortyped Result<Course>state unionrender
這個 project 真正展示的是:TypeScript 提供 static contract,但 runtime boundary 仍需要真實 validation。
6. 為什麼下一課才是 React?
因為現在你已經知道:
- JavaScript runtime 怎麼執行。
- TypeScript 在 runtime 前做什麼。
- UI state 可以用 discriminated union 建模。
- API data 需要 validation。
接下來 React 才是把「state → UI」這件事系統化,而不是拿 JSX 取代你還沒理解的 JavaScript。
Final knowledge check
- TypeScript code 最後一定直接由 Browser 執行嗎?
- source map 解決的是 type error 還是 runtime debugging?
- 如果 CI type check PASS,但 production API shape 改了,為什麼仍可能 crash?
- 畫出 Typed Course API Client 從 request 到 render 的完整資料流。