In the documentation about discriminated unions in typescript, here it says:

Discriminated unions are useful for more than just talking about circles and squares. They’re good for representing any sort of messaging scheme in JavaScript, like when sending messages over the network (client/server communication), ...

Could some explain an example of a messaging scheme that would make use of it?


Messages are usually serialized into bytes and transmitted over a common channel, so when you receive them on the other end, you just have a string that you deserialize back into a useful type.

If you can, for example, receive both GET and POST messages over the same channel, you might want to create a Get and Post class to hold them, so you have a function somewhere like:

function deserialize(receivedBytes: string): Get | Post

This sort of situation is often handled via inheritance, but union types are more flexible and less coupled. For example, you could specify Get | Post in one situation, and Post | Put in another situation, and you don't have to personally have control over the source code for Get, Post, and Put, or restrict yourself to exactly one inheritance hierarchy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.