2 ms·
Afaik they aren't true unions but sum types, which have different implications. And fwiw I've used unions in typescript extensively and I'm not convinced that
by b_e_n_t_o_n 1y ago
Afaik they aren't true unions but sum types, which have different implications.
And fwiw I've used unions in typescript extensively and I'm not convinced that they're a good idea. They give you a certain flexibility to writing code, yes, does that flexibility lead to good design choices, idk.
- kibwen 1y agoTypeScript unions are very different from Rust enums, and they lead to different design decisions. IMO Rust-style tagged unions are essential in any new language coming out today, it's really a pity that people didn't pick up on this in the 70s.
- b_e_n_t_o_n 1y agoWhat differences do they lead to? I just find union types more flexible, with the perceived downside of losing some semantics on success/error results (but I don't think it's a problem personally). But I wouldn't say I'm super knowledgeable about Rust outside of writing some toy programs. You could create your own Result<T, Error> type in TS but people don't really do that outside of ecosystems like Effect because there isn't usually a reason to.
- uzerfcwn 1y agoThe core difference between sums and unions is that sum types have cardinality |A+B| = |A| + |B|, whereas union types have cardinality |A∪B| = |A| + |B| - |A∩B|. As you noted, type systems with union types, such as Typescript, also support sum types because you can create disjoint wrapper types (like Ok and Err) and their union type will be semantically equivalent to a sum type, since the intersection is an empty set. In this sense, union types are strictly more powerful than sum types. The downside is that union types require some notion of subtyping, since otherwise A∩B is always empty for distinct A and B. Unfortunately, subtyping is apparently very difficult to implement in HM-like type systems (like Rust and ML) such that it plays well with type inference.[0] Hence, the downside of having union types in a language is that users have to write out types more often. Unlike kibwen, I don't think Rust's type system is particularly essential for new languages. It's a design choice where one side has more powerful types but the other side has more powerful type inference. [0] https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system#Subtyping https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_sy...