联合类型(A | B)表示"是 A 或 B"。交叉类型(A & B)表示"同时既是 A 又是 B"。
ts
= | | ;
: = ;
() { }
联合类型(A | B)表示"是 A 或 B"。交叉类型(A & B)表示"同时既是 A 又是 B"。
= | | ;
: = ;
() { }
function format(x: string | number) {
// x.toFixed(2); // ❌ toFixed doesn't exist on string
if (typeof x === "number") return x.toFixed(2); // ✅ narrowed to number
return x.toUpperCase(); // ✅ here it's a string
}
在你收窄(narrow)联合类型之前,你只能访问联合类型中每一个成员都具有的属性——编译器会保护你。
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age; // must have BOTH name and age
const p: Person = { name: "Ann", age: 30 }; // both required
交叉类型非常适合用于组合/混合对象类型(例如,为已有类型添加新属性)。
联合类型用于建模"多种可能性中的一种"——这是安全状态建模的基础(例如,用于 reducer 状态的可辨识联合类型)、函数重载以及可空类型(T | null)。
交叉类型则将多个类型组合在一起。
两者结合,使得 TypeScript 的类型系统具有足够的表达力,能够精确地映射真实数据。