据我所知,集合论中取两个集合的并是将这两个集合放在一起形成一个新的集合。取两个集合的交是将它们重叠部分取出来。
对于数字,这个方法也同样适用:
type SomeUnion = (1 | 2 | 3) | (2 | 3 | 4)
const someUnion: SomeUnion // typeof someUnion is 1 | 2 | 3 | 4
type SomeIntersect = (1 | 2 | 3) & (2 | 3 | 4)
const someIntersect: SomeIntersect // typeof someIntersect is 2 | 3
对于对象键,我认为交集和并集操作的工作方式相当不直观。
type ObjUnion = { one: string, two: string } | { two: string, three: string }
const objUnionKeys: keyof ObjUnion // typeof objUnionKeys is 'two' while I would expect it to be all keys -> 'one' | 'two' | 'three'
type ObjIntersection = { one: string, two: string } & { two: string, three: string }
const objIntersectionKeys: keyof ObjIntersection // typeof objIntersectionKeys is 'one' | 'two' | 'three' while I would expect it only to be the keys in common -> 'one'
我想象这样做的原因一定是有根据的。有人能给我解释一下吗?