Hacker News new | ask | show | jobs
by yencabulator 622 days ago
Switching an enum on a `type` field is very much doable and common practice in statically typed languages.

Rust's serde calls that "internally tagged": https://serde.rs/enum-representations.html

1 comments

I specifically said "statically typed programming languages like Java or Golang" because those are languages without constructs that can easily represent something like a Typescript union-of-objects. There are many statically typed programming languages that do support union types!

Rust structured enums qualify - each enum case can have fields, so it's natural to represent a Typescript union type using a Rust enum; It's not quite the same (needs a newtype wrapper for each different combination of types in the union) but is very serviceable for the API use-case.

C and Zig have a different "union" concept where the caller needs to switch on a "tag" field like `type` in Typescript but with less compiler guidance to ensure you use the right union variant for a certain tag value.

Java and Go are more limited. Java can represent an "internally tagged" union as a superclass with subclasses, and Go can represent as an interface type with a method for getting the variant, but both require the consumer to know all the subtypes, and perform their own "if canCast(supertypeValue, unionCaseSubclass1) { // handle case 1 } else if ..." structure, which substantially hinders discoverability and requires more work.