联合类型允许一个值是几种类型之一。英语中的 'or' 直接对应 TypeScript 的 `|`。掌握它,你就能像母语者一样读懂复杂的类型签名。

Union types let a value be one of several things. The English word 'or' maps directly to TypeScript's `|`. Master this and you'll read complex type signatures like native.

📖代码精读

// Union = 'this OR that' — just like English
type Direction = 'north' | 'south' | 'east' | 'west';
type ID = string | number; // accepts both
 
// Discriminated union — the most powerful pattern:
type ApiResult =
| { status: 'success'; data: User }
| { status: 'error'; message: string }
| { status: 'loading' };
 
function handleResult(result: ApiResult) {
if (result.status === 'success') {
console.log(result.data); // TypeScript knows data exists here
} else if (result.status === 'error') {
console.log(result.message); // TypeScript knows message exists here
}
}
 
// 📖 Read ApiResult aloud:
// 'A result is a success with data, OR an error with a message, OR loading'

💡 建议:把每一行代码大声用英文念出来,注释就是你的翻译。

📚单词讲解

union
/ˈjuːnjən/
n.
联合,结合
discriminate
/dɪˈskrɪmɪˌneɪt/
v.
区分,辨别
literal
/ˈlɪtərəl/
adj./n.
字面量(精确匹配的值)
narrow
/ˈnæroʊ/
v.
收窄(缩小类型范围)

🧠理解检验

先在脑子里想一想——再点开看参考答案。

Q1: How does TypeScript know which branch of a discriminated union is active?
Q2: What is the difference between `string | number` and `'north' | 'south' | 'east' | 'west'`?
💡核心要点▼ 展开