TypeScript 型別別名 (Type Alias)
Type Alias (型別別名) 就是幫現有的型別取一個新名字。
基本用法
使用 type 關鍵字:
// 1. 基本型別
type ID = string;
type Age = number;
// 2. 物件型別
type User = {
id: ID;
name: string;
age: Age;
};
// 3. 聯合型別 (Union Types) - 這是 Interface 做不到的!
type Status = 'success' | 'warning' | 'error';
// 4. Tuples (元組) - 這是 Interface 做不到的!
type Coordinate = [number, number];
Type Alias vs Interface
這大概是 TS 面試題前三名。很多時候它們是可以混用的,但有幾個關鍵差異:
| 功能 | Type Alias | Interface |
|---|---|---|
| 定義物件 | type User = { ... } | interface User { ... } |
| 擴充 (Extend) | 使用 & (Intersection) | 使用 extends 關鍵字 |
| 定義 Union | ✅ 可以 (type A = B | C) | ❌ 不行 |
| 定義 Tuple | ✅ 可以 (type C = [A, B]) | ❌ 不行 (很難寫) |
| 宣告合併 | ❌ 不行 (會報錯重複宣告) | ✅ 可以 (自動 merge) |
擴展示範
Interface 使用 extends:
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
Type 使用 & (Intersection):
type Animal = {
name: string;
};
type Dog = Animal & {
bark: () => void;
};
結論:怎麼選?
- 優先使用
interface來定義物件結構(尤其是 public API),因為它的報錯訊息通常比較友善,且支援宣告合併。 - 必須使用
type的情況:- 定義 Union Types (如
type Status = "open" | "closed") - 定義 Primitive Types 別名 (如
type UUID = string) - 定義 Tuples (如
type Point = [x, y]) - 定義 Function Types (雖然 Interface 也可以,但 type 寫起來比較簡潔
type Callback = (data: string) => void)
- 定義 Union Types (如