Hacker News new | ask | show | jobs
by yorwba 3044 days ago
Product and intersection are different things in TypeScript, as well. The product of string and number would be a type like { first: string; second: number }, which combines two different values into one; whereas the intersection string & number is the type of all values that are both strings and numbers.
1 comments

Right, but if we are going to call union types as sum types, why aren’t interesection types called as product types? Anyways, this is why the whole sum type thing breaks down and Union is more apt, since we can describe A|B and A&B using the same terminology family.
A | B and A + B are only "the same" (but not identical) if A and B are disjoint (i.e. there is no value that is in both types). That's why + is also called disjoint union. You can simulate + with | by introducing artificial tags to make A and B disjoint, but in the end they are different operations. TypeScript doesn't really have first-class support for sum types because it needs to remain interoperable with JavaScript, so this simulation is the closest you are going to get.
I agree, so it really isn’t an example of the popularity of sum typing. Typescript does have support for user-supplied tagging, so you can also approximate it to some extent.
Yea, support isn't first class. When I was learning to use union types in TypeScript, initially I wrote custom type guards to distinguish them, using any property that was unique to a particular constituent type to differentiate them.

Nowadays I consider that a mistake, and all unions have a discriminator property, and there is no need for custom type guards (exceptions would be when writing .d.ts files for JS that uses them untagged, that sort of thing) since it makes the code much more explicit.