3 ms·
Help me understand this feature. How does it differ from a discriminated union of object types? (I might be completely misunderstanding the feature you’re raisi
by Waterluvian 5y ago
Help me understand this feature. How does it differ from a discriminated union of object types? (I might be completely misunderstanding the feature you’re raising)
- tshaddox 5y agoTS discriminated unions are functionally nearly identical to variants in OCaml and enums in Rust. I don't know about Rust, but the difference between TS and OCaml is mainly just the syntax and ergonomics. OCaml has great syntax for pattern matching and exhaustiveness checking, for example. You can still get this functionality in TS with if/else or switch statements and potentially some type system tricks: https://www.fullstory.com/blog/discriminated-unions-and-exhaustiveness-checking-in-typescript/ https://www.fullstory.com/blog/discriminated-unions-and-exha... To illustrate how TS discriminated unions are functionally equivalent, check out this playground link showing how ReScript (an alternate syntax of OCaml which can compile to JavaScript) compiles an OCaml variant to a JavaScript object with a "TAG" key that could easily be typed as a discriminated union in TypeScript: https://rescript-lang.org/try?code=C4TwDgpgBAThCOBXCBnYBlYBDYiVQF4oAfKAGQHssATASwDsBzEqdRAY3dRQAo0YGjAJQsAojBgUYAYQrUIPBsCEBuAFBqANhGCwAjIXJU6Tddt0wATIbaduPAEQB1CJvYUAthACEDoVp1YAGZDcUkZOQUAVgAGGKEgA https://rescript-lang.org/try?code=C4TwDgpgBAThCOBXCBnYBlYBD...