top | item 40371655

(no title)

mc10 | 1 year ago

Aren'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.

discuss

order

No comments yet.