Intersection 类型
一句话解释
intersection 类型 (& B) represents 值那个有 所有属性的 两者都类型 and 类型 B. ampersand & 读取 as 'and'.
用大白话说
intersection 类型组合多个类型到 one. 值的 类型 A & B 必须有 所有属性的 AND 所有属性的 B. 你编写它 使用 ampersand: A & B.
Intersections are commonly used for mixins — combining multiple capabilities into a single type. For example, 类型 Timestamped & Identifiable creates a type that has both timestamp properties and ID properties.
When intersecting object types, the result has all properties from all intersected types. When intersecting primitives (like 字符串 & 数字), the result is 从不 because no value can be both a string and a number simultaneously.
示例
type Timestamped = { createdAt: Date };
type Identifiable = { id: string };
type Entity = Timestamped & Identifiable;
const entity: Entity = {
id: "abc-123",
createdAt: new Date(),
};Entity 有两者都 id (从 Identifiable) and createdAt (从 Timestamped).
常见混淆
容易混淆的对象: union 类型
关键区别: Intersection (& B) 需要所有属性的 两者都. Union (| B) 允许属性的 要么, 但仅 常见属性是 accessible 不使用 narrowing.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。