TypeScript Learning

準備 TypeScript 開發環境

⏱️預計 65 分鐘
📖TypeScript 課程
🎯實戰導向

第 2 課:準備 TypeScript 開發環境

學習目標

  • 掌握 Node.js 和 TypeScript 的安裝與配置
  • 理解 tsconfig.json 的核心配置選項
  • 學會建立和管理 TypeScript 專案結構
  • 能夠編譯和執行 TypeScript 程式
  • 了解開發工具和最佳實踐

1. TypeScript 開發環境概述

1.1 為什麼需要開發環境?

TypeScript 是一個編譯型語言,這意味著我們寫的 .ts 檔案不能直接在瀏覽器或 Node.js 中執行,必須先編譯成 JavaScript 才能運行。

開發環境的核心組件:

  1. Node.js - JavaScript 執行環境
  2. TypeScript 編譯器 (tsc) - 將 TypeScript 轉換為 JavaScript
  3. 套件管理器 (npm/yarn) - 管理專案依賴
  4. 程式碼編輯器 - 提供語法高亮和智能提示
  5. 配置檔案 - 控制編譯行為和專案設定

1.2 開發流程概覽

plaintext
1編寫 TypeScript (.ts) → 編譯 (tsc) → 產生 JavaScript (.js) → 執行 (node)

這個流程看似複雜,但一旦設定好環境,大部分步驟都可以自動化。

2. 安裝 Node.js 與套件管理器

2.1 Node.js 安裝

Node.js 是 TypeScript 開發的基礎,它提供:

  • JavaScript 執行環境
  • npm 套件管理器
  • 豐富的生態系統

下載與安裝:

  1. 前往 Node.js 官網
  2. 下載 LTS (Long Term Support) 版本
  3. 執行安裝程式,按照指示完成安裝

版本建議:

  • Node.js 18.x 或更新版本(推薦)
  • Node.js 16.x 最低要求

2.2 驗證安裝

安裝完成後,開啟終端機驗證:

bash
1# 檢查 Node.js 版本
2node --version
3
4# 檢查 npm 版本
5npm --version

預期輸出範例:

plaintext
1v18.17.0
29.6.7

2.3 套件管理器選擇

npm (Node Package Manager)

  • Node.js 內建
  • 最廣泛使用
  • 適合初學者

yarn

  • Facebook 開發
  • 更快的安裝速度
  • 更好的依賴管理

pnpm

  • 節省磁碟空間
  • 更嚴格的依賴管理
  • 適合大型專案

建議: 初學者使用 npm,熟悉後可以嘗試其他選項。

3. TypeScript 編譯器安裝

3.1 全域安裝 vs 專案安裝

全域安裝 (Global Installation)

bash
1# 使用 npm
2npm install -g typescript
3
4# 使用 yarn
5yarn global add typescript
6
7# 驗證安裝
8tsc --version

優點:

  • 可在任何地方使用 tsc 指令
  • 適合快速測試和學習

缺點:

  • 版本衝突問題
  • 團隊協作困難
  • 不利於專案管理

專案安裝 (Project Installation) - 推薦

bash
1# 初始化專案
2npm init -y
3
4# 安裝 TypeScript 為開發依賴
5npm install typescript --save-dev
6
7# 使用 npx 執行
8npx tsc --version

優點:

  • 每個專案獨立版本
  • 團隊協作友好
  • 版本控制一致性

缺點:

  • 需要使用 npx 或配置 scripts

3.2 專案結構建議

plaintext
1my-typescript-project/
2├── src/                 # TypeScript 原始碼
3│   ├── index.ts
4│   ├── utils/
5│   └── types/
6├── dist/                # 編譯輸出
7├── node_modules/        # 依賴套件
8├── package.json         # 專案配置
9├── tsconfig.json        # TypeScript 配置
10└── README.md           # 專案說明

4. tsconfig.json 深度解析

4.1 什麼是 tsconfig.json?

tsconfig.json 是 TypeScript 專案的配置中心,它告訴編譯器:

  • 哪些檔案需要編譯
  • 如何編譯這些檔案
  • 編譯後的檔案放在哪裡
  • 啟用哪些語言特性

4.2 生成基本配置

bash
1# 生成預設的 tsconfig.json
2npx tsc --init

這會創建一個包含詳細註解的配置檔案。

4.3 核心配置選項詳解

編譯目標 (target)

json
1{
2  "compilerOptions": {
3    "target": "ES2020"
4  }
5}

常用選項:

  • ES5 - 支援舊瀏覽器
  • ES2015/ES6 - 現代瀏覽器基本支援
  • ES2020 - 推薦選項,平衡兼容性和功能
  • ESNext - 最新特性

模組系統 (module)

json
1{
2  "compilerOptions": {
3    "module": "ESNext"
4  }
5}

常用選項:

  • CommonJS - Node.js 傳統模組系統
  • ESNext - 現代 ES 模組(推薦)
  • UMD - 通用模組定義

嚴格模式 (strict)

json
1{
2  "compilerOptions": {
3    "strict": true
4  }
5}

強烈建議啟用! 包含:

  • noImplicitAny - 禁止隱式 any 類型
  • strictNullChecks - 嚴格空值檢查
  • strictFunctionTypes - 嚴格函數類型檢查

輸出配置

json
1{
2  "compilerOptions": {
3    "outDir": "./dist",
4    "rootDir": "./src"
5  }
6}
  • outDir - 編譯輸出目錄
  • rootDir - 原始碼根目錄

模組解析增強

json
1{
2  "compilerOptions": {
3    "esModuleInterop": true,
4    "allowSyntheticDefaultImports": true,
5    "moduleResolution": "node"
6  }
7}

4.4 完整配置範例

json
1{
2  "compilerOptions": {
3    // 基本選項
4    "target": "ES2020",
5    "module": "ESNext",
6    "lib": ["ES2020", "DOM"],
7    
8    // 嚴格檢查
9    "strict": true,
10    "noUnusedLocals": true,
11    "noUnusedParameters": true,
12    "noImplicitReturns": true,
13    
14    // 模組解析
15    "moduleResolution": "node",
16    "esModuleInterop": true,
17    "allowSyntheticDefaultImports": true,
18    
19    // 輸出配置
20    "outDir": "./dist",
21    "rootDir": "./src",
22    "sourceMap": true,
23    "declaration": true,
24    
25    // 路徑映射
26    "baseUrl": "./",
27    "paths": {
28      "@/*": ["src/*"],
29      "@utils/*": ["src/utils/*"]
30    },
31    
32    // 性能優化
33    "skipLibCheck": true,
34    "forceConsistentCasingInFileNames": true
35  },
36  "include": ["src/**/*"],
37  "exclude": ["node_modules", "dist", "**/*.test.ts"]
38}

5. 開發工具與編輯器

5.1 推薦編輯器

Visual Studio Code (推薦)

  • 微軟官方支援
  • 內建 TypeScript 支援
  • 豐富的擴充套件生態

其他選擇:

  • WebStorm (JetBrains)
  • Sublime Text
  • Atom
  • Vim/Neovim

5.2 VS Code 必備擴充套件

  1. TypeScript Importer - 自動導入
  2. Prettier - 程式碼格式化
  3. ESLint - 程式碼品質檢查
  4. Auto Rename Tag - 標籤同步重命名
  5. Bracket Pair Colorizer - 括號配對高亮

5.3 VS Code 設定建議

json
1{
2  "typescript.preferences.importModuleSpecifier": "relative",
3  "typescript.suggest.autoImports": true,
4  "typescript.updateImportsOnFileMove.enabled": "always",
5  "editor.formatOnSave": true,
6  "editor.codeActionsOnSave": {
7    "source.organizeImports": true
8  }
9}

6. 專案初始化實戰

6.1 建立新專案

bash
1# 建立專案目錄
2mkdir my-typescript-app
3cd my-typescript-app
4
5# 初始化 npm 專案
6npm init -y
7
8# 安裝 TypeScript
9npm install typescript --save-dev
10
11# 安裝 Node.js 類型定義
12npm install @types/node --save-dev
13
14# 生成 tsconfig.json
15npx tsc --init

6.2 設定 package.json scripts

json
1{
2  "scripts": {
3    "build": "tsc",
4    "start": "node dist/index.js",
5    "dev": "tsc --watch",
6    "clean": "rm -rf dist"
7  }
8}

scripts 說明:

  • build - 編譯 TypeScript
  • start - 執行編譯後的程式
  • dev - 監視模式編譯
  • clean - 清理輸出目錄

7. 常見問題與解決方案

7.1 編譯錯誤

問題:找不到模組

plaintext
1error TS2307: Cannot find module 'lodash'

解決方案:

bash
1# 安裝套件和類型定義
2npm install lodash
3npm install @types/lodash --save-dev

問題:隱式 any 類型

plaintext
1error TS7006: Parameter 'x' implicitly has an 'any' type

解決方案:

typescript
1// 錯誤
2function add(x, y) {
3  return x + y;
4}
5
6// 正確
7function add(x: number, y: number): number {
8  return x + y;
9}

7.2 路徑解析問題

問題:相對路徑過長

typescript
1import { utils } from '../../../utils/helpers';

解決方案:使用路徑映射

json
1// tsconfig.json
2{
3  "compilerOptions": {
4    "baseUrl": "./",
5    "paths": {
6      "@utils/*": ["src/utils/*"]
7    }
8  }
9}
typescript
1// 使用別名
2import { utils } from '@utils/helpers';

7.3 性能優化

問題:編譯速度慢

解決方案:

  1. 啟用 skipLibCheck
  2. 使用 incremental 編譯
  3. 排除不必要的檔案
json
1{
2  "compilerOptions": {
3    "skipLibCheck": true,
4    "incremental": true
5  },
6  "exclude": ["node_modules", "**/*.test.ts"]
7}

8. 最佳實踐

8.1 專案結構

plaintext
1src/
2├── components/          # 元件
3├── services/           # 服務層
4├── types/              # 類型定義
5├── utils/              # 工具函數
6├── constants/          # 常數
7└── index.ts           # 入口檔案

8.2 命名規範

  • 檔案名稱: kebab-case (user-service.ts)
  • 類別名稱: PascalCase (UserService)
  • 函數名稱: camelCase (getUserData)
  • 常數名稱: UPPER_SNAKE_CASE (API_BASE_URL)

8.3 類型定義組織

typescript
1// types/user.ts
2export interface User {
3  id: number;
4  name: string;
5  email: string;
6}
7
8export type UserRole = 'admin' | 'user' | 'guest';

8.4 環境變數管理

typescript
1// config/environment.ts
2export const config = {
3  apiUrl: process.env.API_URL || 'http://localhost:3000',
4  isDevelopment: process.env.NODE_ENV === 'development'
5};

互動練習

練習 1:環境檢查

檢查你的開發環境是否正確安裝。

typescript
1type: simple_run
2instruction: 執行以下程式碼來檢查你的 TypeScript 環境。觀察輸出結果,確認版本資訊。
3---
4// 檢查 TypeScript 環境
5console.log('=== TypeScript 環境檢查 ===');
6
7// 檢查 Node.js 版本
8console.log('Node.js 版本:', process.version);
9
10// 檢查 TypeScript 編譯器版本(模擬)
11console.log('TypeScript 版本: 5.2.2');
12
13// 檢查當前工作目錄
14console.log('當前目錄:', process.cwd());
15
16// 檢查環境變數
17console.log('環境:', process.env.NODE_ENV || 'development');
18
19console.log('✅ 環境檢查完成!');
typescript
1// 這個練習主要是讓你熟悉環境檢查的概念
2// 在實際開發中,你可以在終端機執行:
3// node --version
4// npx tsc --version
5// 來檢查實際的版本資訊

練習 2:建立基本專案結構

體驗建立 TypeScript 專案的基本步驟。

typescript
1type: simple_run
2instruction: 模擬建立專案結構的過程。觀察每個步驟的輸出,理解專案初始化流程。
3---
4// 模擬專案初始化過程
5console.log('🚀 開始建立 TypeScript 專案...\n');
6
7// 步驟 1: 建立專案目錄
8console.log('📁 建立專案目錄: my-typescript-app');
9
10// 步驟 2: 初始化 npm
11console.log('📦 初始化 npm 專案...');
12const packageJson = {
13  name: 'my-typescript-app',
14  version: '1.0.0',
15  description: 'My first TypeScript project',
16  main: 'dist/index.js',
17  scripts: {
18    build: 'tsc',
19    start: 'node dist/index.js',
20    dev: 'tsc --watch'
21  }
22};
23console.log('✅ package.json 已建立');
24
25// 步驟 3: 安裝 TypeScript
26console.log('⬇️  安裝 TypeScript...');
27console.log('✅ TypeScript 安裝完成');
28
29// 步驟 4: 建立 tsconfig.json
30console.log('⚙️  建立 tsconfig.json...');
31const tsConfig = {
32  compilerOptions: {
33    target: 'ES2020',
34    module: 'ESNext',
35    outDir: './dist',
36    rootDir: './src',
37    strict: true
38  }
39};
40console.log('✅ tsconfig.json 已建立');
41
42// 步驟 5: 建立目錄結構
43console.log('📂 建立目錄結構...');
44const directories = ['src', 'dist', 'src/utils', 'src/types'];
45directories.forEach(dir => {
46  console.log(`${dir}/`);
47});
48
49console.log('\n🎉 專案建立完成!');
50console.log('下一步:在 src/ 目錄中開始編寫 TypeScript 程式碼');
typescript
1// 實際的專案建立指令:
2// mkdir my-typescript-app
3// cd my-typescript-app
4// npm init -y
5// npm install typescript --save-dev
6// npx tsc --init
7// mkdir src dist

練習 3:tsconfig.json 配置實驗

嘗試不同的編譯器選項,觀察它們的效果。

typescript
1type: output_check
2instruction: 完成 tsconfig.json 配置函數,根據專案類型返回適當的配置。
3expectedOutput: {"target":"ES2020","module":"ESNext","strict":true,"outDir":"./dist","rootDir":"./src","esModuleInterop":true}
4---
5// 根據專案類型生成 tsconfig.json 配置
6function generateTsConfig(projectType: 'web' | 'node' | 'library'): object {
7  const baseConfig = {
8    target: 'ES2020',
9    module: 'ESNext',
10    strict: true,
11    outDir: './dist',
12    rootDir: './src'
13  };
14
15  // 根據專案類型添加特定配置
16  if (projectType === 'web') {
17    return {
18      ...baseConfig,
19      lib: ['ES2020', 'DOM'],
20      esModuleInterop: true
21    };
22  } else if (projectType === 'node') {
23    return {
24      ...baseConfig,
25      esModuleInterop: true  // 補充這行
26    };
27  } else if (projectType === 'library') {
28    return {
29      ...baseConfig,
30      declaration: true,
31      esModuleInterop: true
32    };
33  }
34
35  return baseConfig;
36}
37
38// 測試 Node.js 專案配置
39const nodeConfig = generateTsConfig('node');
40console.log(JSON.stringify(nodeConfig));
typescript
1function generateTsConfig(projectType: 'web' | 'node' | 'library'): object {
2  const baseConfig = {
3    target: 'ES2020',
4    module: 'ESNext',
5    strict: true,
6    outDir: './dist',
7    rootDir: './src'
8  };
9
10  if (projectType === 'web') {
11    return {
12      ...baseConfig,
13      lib: ['ES2020', 'DOM'],
14      esModuleInterop: true
15    };
16  } else if (projectType === 'node') {
17    return {
18      ...baseConfig,
19      esModuleInterop: true  // Node.js 專案需要這個選項來改善模組互操作性
20    };
21  } else if (projectType === 'library') {
22    return {
23      ...baseConfig,
24      declaration: true,      // 生成 .d.ts 檔案
25      esModuleInterop: true
26    };
27  }
28
29  return baseConfig;
30}

練習 4:編譯流程模擬

理解從 TypeScript 到 JavaScript 的編譯過程。

typescript
1type: output_check
2instruction: 完成編譯器模擬函數,將 TypeScript 程式碼轉換為 JavaScript。
3expectedOutput: function greet(name) { return "Hello, " + name + "!"; }
4---
5// 模擬 TypeScript 編譯器的簡化版本
6function simulateCompiler(tsCode: string, target: 'ES5' | 'ES2020'): string {
7  // 移除類型註解
8  let jsCode = tsCode.replace(/:\s*\w+/g, '');
9  
10  if (target === 'ES5') {
11    // 將箭頭函數轉換為普通函數
12    jsCode = jsCode.replace(/const\s+(\w+)\s*=\s*\(([^)]*)\)\s*=>\s*{([^}]*)}/g, 
13      'function $1($2) {$3}');
14    
15    // 將樣板字串轉換為字串連接
16    jsCode = jsCode.replace(/`([^`]*)\$\{([^}]+)\}([^`]*)`/g, '"$1" + $2 + "$3"');
17  }
18  
19  return jsCode.trim();
20}
21
22// 測試編譯
23const tsCode = 'function greet(name: string): string { return `Hello, ${name}!`; }';
24const compiledCode = simulateCompiler(tsCode, 'ES5');
25console.log(compiledCode);
typescript
1function simulateCompiler(tsCode: string, target: 'ES5' | 'ES2020'): string {
2  // 移除類型註解(: string, : number 等)
3  let jsCode = tsCode.replace(/:\s*\w+/g, '');
4  
5  if (target === 'ES5') {
6    // 將箭頭函數轉換為普通函數
7    jsCode = jsCode.replace(/const\s+(\w+)\s*=\s*\(([^)]*)\)\s*=>\s*{([^}]*)}/g, 
8      'function $1($2) {$3}');
9    
10    // 將樣板字串轉換為字串連接
11    // 這個正則表達式匹配 `Hello, ${name}!` 並轉換為 "Hello, " + name + "!"
12    jsCode = jsCode.replace(/`([^`]*)\$\{([^}]+)\}([^`]*)`/g, '"$1" + $2 + "$3"');
13  }
14  
15  return jsCode.trim();
16}
17
18// 這個函數展示了 TypeScript 編譯器的基本工作原理:
19// 1. 移除類型註解
20// 2. 根據目標版本轉換語法特性
21// 3. 輸出相容的 JavaScript 程式碼

練習 5:專案配置管理器

建立一個完整的專案配置管理系統。

typescript
1type: output_check
2instruction: 完成專案配置管理器,能夠驗證和生成完整的專案配置。
3expectedOutput: ✅ 配置驗證通過!專案類型: web, 嚴格模式: 啟用, 輸出目錄: ./dist
4---
5interface ProjectConfig {
6  name: string;
7  type: 'web' | 'node' | 'library';
8  typescript: {
9    strict: boolean;
10    target: string;
11    outDir: string;
12  };
13}
14
15class ProjectConfigManager {
16  private config: ProjectConfig;
17
18  constructor(config: ProjectConfig) {
19    this.config = config;
20  }
21
22  validate(): boolean {
23    // 檢查必要欄位
24    if (!this.config.name || !this.config.type) {
25      return false;
26    }
27
28    // 檢查 TypeScript 配置
29    if (!this.config.typescript.target || !this.config.typescript.outDir) {
30      return false;
31    }
32
33    return true;
34  }
35
36  generateReport(): string {
37    if (!this.validate()) {
38      return '❌ 配置驗證失敗!';
39    }
40
41    const strictMode = this.config.typescript.strict ? '啟用' : '停用';
42    return `✅ 配置驗證通過!專案類型: ${this.config.type}, 嚴格模式: ${strictMode}, 輸出目錄: ${this.config.typescript.outDir}`;
43  }
44}
45
46// 測試配置管理器
47const config: ProjectConfig = {
48  name: 'my-web-app',
49  type: 'web',
50  typescript: {
51    strict: true,  // 補充這行
52    target: 'ES2020',
53    outDir: './dist'
54  }
55};
56
57const manager = new ProjectConfigManager(config);
58console.log(manager.generateReport());
typescript
1interface ProjectConfig {
2  name: string;
3  type: 'web' | 'node' | 'library';
4  typescript: {
5    strict: boolean;
6    target: string;
7    outDir: string;
8  };
9}
10
11class ProjectConfigManager {
12  private config: ProjectConfig;
13
14  constructor(config: ProjectConfig) {
15    this.config = config;
16  }
17
18  validate(): boolean {
19    // 檢查必要欄位
20    if (!this.config.name || !this.config.type) {
21      return false;
22    }
23
24    // 檢查 TypeScript 配置
25    if (!this.config.typescript.target || !this.config.typescript.outDir) {
26      return false;
27    }
28
29    return true;
30  }
31
32  generateReport(): string {
33    if (!this.validate()) {
34      return '❌ 配置驗證失敗!';
35    }
36
37    const strictMode = this.config.typescript.strict ? '啟用' : '停用';
38    return `✅ 配置驗證通過!專案類型: ${this.config.type}, 嚴格模式: ${strictMode}, 輸出目錄: ${this.config.typescript.outDir}`;
39  }
40
41  // 額外方法:生成 tsconfig.json
42  generateTsConfig(): object {
43    return {
44      compilerOptions: {
45        target: this.config.typescript.target,
46        outDir: this.config.typescript.outDir,
47        strict: this.config.typescript.strict,
48        module: 'ESNext',
49        esModuleInterop: true
50      }
51    };
52  }
53}
54
55// 這個類別展示了如何管理複雜的專案配置
56// 包括驗證、報告生成和配置檔案產生

練習 6:開發工具整合

體驗完整的開發工具鏈整合。

typescript
1type: simple_run
2instruction: 模擬完整的開發工具鏈,包括編譯、檢查和執行。體驗現代 TypeScript 開發流程。
3---
4// 模擬開發工具鏈
5class DevelopmentToolchain {
6  private projectName: string;
7  private files: string[] = [];
8
9  constructor(projectName: string) {
10    this.projectName = projectName;
11  }
12
13  // 添加檔案到專案
14  addFile(filename: string): void {
15    this.files.push(filename);
16    console.log(`📄 添加檔案: ${filename}`);
17  }
18
19  // 模擬 TypeScript 編譯
20  compile(): boolean {
21    console.log('🔨 開始編譯 TypeScript...');
22    
23    // 模擬編譯過程
24    for (const file of this.files) {
25      console.log(`  ✅ 編譯 ${file}`);
26    }
27    
28    console.log('✅ 編譯完成!');
29    return true;
30  }
31
32  // 模擬程式碼檢查
33  lint(): boolean {
34    console.log('🔍 執行程式碼檢查...');
35    console.log('  ✅ 沒有發現問題');
36    return true;
37  }
38
39  // 模擬測試執行
40  test(): boolean {
41    console.log('🧪 執行測試...');
42    console.log('  ✅ 所有測試通過');
43    return true;
44  }
45
46  // 完整的建置流程
47  build(): void {
48    console.log(`🚀 開始建置專案: ${this.projectName}\n`);
49    
50    if (this.compile() && this.lint() && this.test()) {
51      console.log('\n🎉 建置成功!專案已準備好部署');
52    } else {
53      console.log('\n❌ 建置失敗!請檢查錯誤訊息');
54    }
55  }
56}
57
58// 模擬開發流程
59const toolchain = new DevelopmentToolchain('my-awesome-app');
60
61toolchain.addFile('src/index.ts');
62toolchain.addFile('src/utils/helpers.ts');
63toolchain.addFile('src/types/user.ts');
64
65toolchain.build();
typescript
1// 這個練習展示了現代 TypeScript 開發的完整工具鏈
2// 在實際開發中,你會使用:
3// - tsc 或 webpack/vite 進行編譯
4// - ESLint 進行程式碼檢查
5// - Jest 或 Vitest 進行測試
6// - npm scripts 或 GitHub Actions 進行自動化建置
7
8// 實際的 package.json scripts 範例:
9// {
10//   "scripts": {
11//     "build": "tsc",
12//     "lint": "eslint src/**/*.ts",
13//     "test": "jest",
14//     "dev": "tsc --watch"
15//   }
16// }

練習 7:環境配置測驗

測試你對 TypeScript 開發環境的理解。

typescript
1type: output_check
2instruction: 回答關於 TypeScript 開發環境的問題,修正錯誤的配置。
3expectedOutput: 正確答案: B, A, C, A
4---
5// TypeScript 開發環境測驗
6class EnvironmentQuiz {
7  private answers: string[] = [];
8
9  // 問題 1: 哪個是推薦的 TypeScript 安裝方式?
10  question1(): string {
11    const options = {
12      A: '全域安裝,方便在任何地方使用',
13      B: '專案內安裝,避免版本衝突',
14      C: '兩種都可以,沒有差別'
15    };
16    
17    // 正確答案是 B
18    return 'B';
19  }
20
21  // 問題 2: strict 模式應該設定為?
22  question2(): string {
23    const options = {
24      A: 'true - 啟用嚴格檢查',
25      B: 'false - 避免編譯錯誤',
26      C: '看情況決定'
27    };
28    
29    // 正確答案是 A
30    return 'A';
31  }
32
33  // 問題 3: 現代專案推薦的模組系統是?
34  question3(): string {
35    const options = {
36      A: 'CommonJS',
37      B: 'AMD',
38      C: 'ESNext'
39    };
40    
41    // 正確答案是 C
42    return 'C';
43  }
44
45  // 問題 4: tsconfig.json 的 outDir 用途是?
46  question4(): string {
47    const options = {
48      A: '指定編譯輸出目錄',
49      B: '指定原始碼目錄',
50      C: '指定模組解析目錄'
51    };
52    
53    // 正確答案是 A
54    return 'A';
55  }
56
57  // 生成測驗結果
58  generateResults(): string {
59    const answers = [
60      this.question1(),
61      this.question2(), 
62      this.question3(),
63      this.question4()
64    ];
65    
66    return `正確答案: ${answers.join(', ')}`;
67  }
68}
69
70const quiz = new EnvironmentQuiz();
71console.log(quiz.generateResults());
typescript
1class EnvironmentQuiz {
2  // 問題解析:
3  
4  // 問題 1: 專案內安裝 TypeScript 的優勢
5  // - 每個專案可以有獨立的 TypeScript 版本
6  // - 避免全域版本衝突
7  // - 團隊協作時版本一致性
8  // - 可以在 package.json 中鎖定版本
9  
10  // 問題 2: strict 模式的重要性
11  // - 啟用所有嚴格類型檢查
12  // - 幫助早期發現潛在問題
13  // - 提升程式碼品質和可維護性
14  // - 雖然初期可能有更多錯誤,但長期有益
15  
16  // 問題 3: ESNext 模組系統的優勢
17  // - 現代 JavaScript 標準
18  // - 更好的樹搖優化 (tree shaking)
19  // - 靜態分析友好
20  // - 與現代打包工具相容性更好
21  
22  // 問題 4: outDir 配置
23  // - 指定編譯後 JavaScript 檔案的輸出位置
24  // - 通常設定為 './dist' 或 './build'
25  // - 與 rootDir 配合使用維持目錄結構
26}

總結

在這一課中,我們深入學習了 TypeScript 開發環境的建立和配置:

關鍵要點

  1. 環境組件:Node.js、TypeScript 編譯器、套件管理器、編輯器
  2. 安裝策略:推薦專案內安裝 TypeScript,避免版本衝突
  3. 配置核心:tsconfig.json 是專案配置的中心
  4. 最佳實踐:啟用嚴格模式、使用現代模組系統、合理的專案結構

下一步

  • 熟練使用 VS Code 和 TypeScript
  • 探索更多編譯器選項
  • 學習專案自動化工具
  • 開始編寫實際的 TypeScript 程式碼

準備好了嗎?讓我們在下一課深入學習 TypeScript 的基本類型系統!