根据我对集合论的了解,当您将两个集合进行并集时,您将覆盖两个集合并获取结果集。取两个集合的交集时,将两个集合重叠,然后取取彼此重叠的部分。
对于数字,这很好用:
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'
我认为它有这样一个可靠的原因。有人可以填写我吗?
答案 0 :(得分:4)
您是对的,对象的并集和相交的行为似乎与文字的行为完全相反,但这实际上是很有意义的:)让我们深入研究为什么!
如果您有字符串或数字文字的联合类型à
type SomeUnion = 1 | 2 | 3 | 2 | 3 | 4
您要说的是SomeUnion
可以是这些数字中的任何一个。
有空的时候
type SomeIntersect = (1 | 2 | 3) & (2 | 3 | 4)
您要说的是SomeIntersect
必须满足两个组的约束。在这种情况下,同时满足这两个条件的唯一数字是2和3,因此上述值等于type SomeIntersect = 2 | 3
尽管并集和交集的语义对于对象来说是不同的。
有空的时候
type ObjUnion = { one: string, two: string } | { two: string, three: string }
您要说的是ObjUnion
可以具有任一个的形状-意味着您确定知道的唯一字段ObjUnion
是"two"
。其他形状可能存在或不存在,具体取决于它实际上是两种形状中的哪一种。但是您可以肯定{ two: string }
存在于对象上。
涉及到
type ObjIntersection = { one: string, two: string } & { two: string, three: string }
您要说的是ObjIntersection
必须在这两个对象类型中具有所有3个字段,否则将无法满足交集的约束。
这意味着,如果您有一个ObjIntersection
类型的对象,您就会知道它具有所有3个字段,因此TypeScript可以让您毫无问题地访问其中的任何一个!>