DEV Community

Discussion on: The meaning of union and intersection types

Collapse
anduser96 profile image
Andrei Gatej

This was a great article! Thank you.

I’m still not 100% sure I understood the union of 2 sets of objects.

So if you have Foo | Bar, wouldn’t it be similar to saying: just collect the objects from both sets?
Then, the intersection would result in { { xyz, foo }, { xyz, bar } }, right? Then, how can one infer that the actually resulted set would only be { xyz }? 🤔

Collapse
miloszpp profile image
Milosz Piechocki Author

Thanks!

Union would indeed contain all objects from both sets. However, the only thing we can know for sure about these objects is that they must contain the xyz property. Therefore, the type is { xyz: string }.

TypeScript has the concept of type assignability. An object type is assignable to { xyz: string } type even if it has some excess properties (there are exceptions, though - see here). So, all objects from both union members are assignable to { xyz: string } type.

Collapse
anduser96 profile image
Andrei Gatej

I think I finally understood it!

So it’s typescript’s magic that translates a union that resulted from a mathematical point of view into a single type that all the other types are assignable to.

So, without typescript, I’d get { { xyz, foo }, { xyz, bar } }, but after typescript weighs in, the resulted type will only be { xyz: string }.

I hope I got it right.

Thank you!

Thread Thread
miloszpp profile image
Milosz Piechocki Author

Yeah, I think you've got it right :)