TS 中交集和并集在对象类型中的使用差异

TS 中交集和并集在对象类型中的使用差异

TL, DR

  • 对象类型中使用 | ,效果等同于取交集
  • 对象类型中使用 & ,效果等同于取并集

对象类型中使用联合类型 |

使用联合类型时,官网有以下解释 Working with Union Types

It might be confusing that a union of types appears to have the intersection of those types’ properties. This is not an accident - the name union comes from type theory.

1
2
3
4
5
6
7
8
9
10
11
type Foo = {
name: string
age: string
}
type Bar = {
name: string
age: string
gender: number
}

type result = keyof (Foo | Bar) // "name" | "age"

对象类型中使用交集类型 &

使用交集类型时,可以看 Intersection Types 的 demo

1
2
3
4
5
6
7
8
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}

type ColorfulCircle = keyof (Colorful & Circle) // "color" | "radius"