联合类型(Union)与交叉类型(Intersection)分别是什么?
- 联合
A | B:取值可以是 A 或 B(满足任一即可) - 交叉
A & B:同时满足 A 和 B(属性合并)
type Status = 'loading' | 'success' | 'error' // 联合
type User = { name: string } & { age: number } // 交叉 => { name, age }收窄(narrowing):对联合类型,用 typeof / in / 类型守卫把宽泛类型缩到具体分支:
function format(x: string | number) {
if (typeof x === 'string') return x.toUpperCase() // 此处 x 是 string
return x.toFixed(2) // 此处 x 是 number
}交叉若含 never 或属性类型冲突会变为
never(如string & number)。