Union(聯合型別) 與 Intersection(交叉型別)
Union(聯合型別): |
定義與用法
Union(聯合型別) 用於表示一個變量可以是幾種不同型別中的一種。在 TypeScript 中,使用 |
符號來表示。
let value: string | number;
value = 'Hello'; // 合法
value = 42; // 合法
value = true; // 錯誤,型別不匹配
Union 的行為類似於布林邏輯中的 OR
操作,即變數可以是多種類型中的任意一種。
常見 應用場景與例子
Union 常見的應用場景包括:
-
定義一個函數的參數可以接受多種不同型別,以處理不同 API 返回值的類型
function formatValue(value: string | number): string {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value.toFixed(2);
} -
當配置物件可以接受多種不同類型的值時,可以使用 Union來描述這些配置選項
type ConfigOption = 'auto' | 'manual' | 'none';
interface Config {
mode: ConfigOption;
}
const config: Config = {
mode: 'auto'
};
Intersection(交集型別): &
定義與用法
Intersection(交叉型別) 用於表示一個變數必須同時滿足多個類型的條件。在 TypeScript 中,使用 &
符號來表示。
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type EmployeePerson = Person & Employee;
const john: EmployeePerson = {
name: 'John',
employeeId: 123
};