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."
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.
It 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.
mc10|1 year ago
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.
anamexis|1 year ago
stiiv|1 year ago
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.