Hacker News new | ask | show | jobs
by ronenlh 1775 days ago
The Sum is called Union in the TypeScript docs, as it narrows the valid values to the overlapping elements.

In the switch statement it becomes a Sum value (as shown in the article).

In ReScript (shown as well, which uses OCaml under the hood) the syntax is that of a Variant, in which each element is a different nominal type.

1 comments

Good point. For example,

    type NotAProduct = Bool | Bool
only has 2 values, not 4. For a real product type, we need

    type Product = {tag: "Left", value: Bool} | {tag: "Right", value: Bool}
which has the requisite 4 values.
This is also called a "discriminated union", with "tag" being the discriminator here.
So to replicate a Rust enum, C tagged union, or C++ std::variant containing one byte for the type and the rest of the object inline, JavaScript needs a boxed object wrapping a string and the actual object contained inside? And the engine can't optimize away the boxed object into an inline value type because it could have multiple aliasing references in multiple locations? Boxing-based languages make me sad.