Union and Intersection 类型
组合类型使用 unions (| B) and intersections (& B) for flexible 类型 modeling.
你将学到
- 如何 union 类型 (| B) let 值是 one 的几个类型
- 如何 intersection 类型 (& B) 组合多个类型到 one
- Using 字符串 literal unions for enums-如模式
- Narrowing union 类型使用类型 guards
概念讲解
Union Types
A union type ( | B) means a value can be either type A or type B. For example, 类型 ID = 数字 | 字符串 allows an ID that is either a number or a string. Union types are extremely common for function parameters that accept multiple input shapes, return types that can be different things, and string literal unions like 类型 方向 = "左" | "正确" | "上" | "下" which act as a lightweight enum.
Intersection Types
An intersection type ( & B) combines all properties of A and B into a single type — a value must satisfy both. For example, 类型 Admin = 用户 & { permissions: 字符串[] } has all properties of 用户 plus permissions. Intersections are the type-alias equivalent of interface extends. They are useful for composing types from smaller pieces, especially when combining types from different sources.
Narrowing Unions
When you have a union type, TypeScript needs to know which specific type is in play before you can access type-specific properties. This is called narrowing. You narrow with type guards: typeof checks for primitives, in operator for property presence, and instanceof for classes. The compiler tracks these checks and gives you the narrowed type inside each branch.
示例代码
// Union — a value can be one of several types.
type ID = number | string;
function formatId(id: ID): string {
return String(id);
}
// String literal union — acts like a lightweight enum.
type Direction = "left" | "right" | "up" | "down";
function move(dir: Direction): void {
console.log("Moving", dir);
}
// Intersection — combines all properties from both types.
type Timestamps = { createdAt: Date; updatedAt: Date };
type User = { id: number; name: string };
type UserRecord = User & Timestamps;
const record: UserRecord = {
id: 1,
name: "Alice",
createdAt: new Date(),
updatedAt: new Date(),
};
move("left");
console.log(formatId(42), formatId("abc"));
Unions (|) 允许 one 的几个类型. Intersections (&) 需要所有属性从 每个类型. 字符串 literal unions 是 lightweight alternative 到 enums.
动手试一试
- JSON 到 TypeScript
API 响应经常 produce union 类型 for 可选 or polymorphic 字段.
- JSON Schema Validator
验证数据 shapes 那个 match 你的 union and intersection 类型.
常见错误
错误写法
Accessing 属性那个仅 exist on one 边的 union 不使用 narrowing
正确做法
Use 类型 guard (typeof, in, instanceof) 到 narrow union 首先. 编译器然后 lets 你 access 类型-特定属性内部那个分支.
错误写法
创建 intersections 的 incompatible 类型那个 result in 从不
正确做法
如果 two 类型有 conflicting 属性类型 (e.g. 字符串对比数字 for 相同键), 它们的 intersection becomes 从不. 检查 for 属性 name conflicts.
练习 Union and Intersection 类型
9 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。