7 ms·
Sure! You need a `type` field (or something like it) in TS. You don't need that in a language like F# -- the discrimation occurs strictly in virtue of your uni
by stiiv 2y ago
Sure! You need a `type` field (or something like it) in TS.
You don't need that in a language like F# -- the discrimation occurs strictly in virtue of your union definition. That's what I meant by "native support."
- anamexis 2y agoIsn’t it the same in TypeScript? You don’t need an explicit type field.
- stiiv 2y agoIt depends on what you're trying to achieve. If there are sufficient structural differences, you're fine (`"foo" in myThing` can discrimate) but if two types in your union have the same structure, TS doesn't give you a way to tell them apart. (This relates back to branded types.) A good example would be `type Money = Dollars | Euros` where both types in the union alias `number`. You need a tag. In other languages, you don't.
- anamexis 2y agoTrue, although I think that's just missing branded types, not discriminated unions.
- mc10 2y agoAren't these two forms isomorphic: type MyUnion = { type: "foo"; foo: string } | { type: "bar"; bar: string }; vs type MyUnion = Foo of { foo: string } | Bar of { bar: string }; You still need some runtime encoding of which branch of the union your data is; otherwise, your code could not pick a branch at runtime. There's a slight overhead to the TypeScript version (which uses strings instead of an int to represent the branch) but it allows discriminated unions to work without having to introduce them as a new data type into JavaScript. And if you really wanted to, you could use a literal int as the `type` field instead.