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.
联合类型允许一个值是几种类型之一。英语中的 'or' 直接对应 TypeScript 的 `|`。掌握它,你就能像母语者一样读懂复杂的类型签名。
Read the Code
// 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'
💡 Tip: read each line aloud in English. The comments are your guide.
Vocabulary Focus
union
/ˈjuːnjən/
n.
联合,结合
discriminate
/dɪˈskrɪmɪˌneɪt/
v.
区分,辨别
literal
/ˈlɪtərəl/
adj./n.
字面量(精确匹配的值)
narrow
/ˈnæroʊ/
v.
收窄(缩小类型范围)
Comprehension Check
Answer in your head first — then reveal to see the model answer.
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'`?
Key Insight▼ Reveal