“Hands create art on a pottery wheel” by on SwapnIl Dwivedi Unsplash Clear, clean and concise, are some of the adjectives I would associate with an API that makes for a pleasant and productive experience. development TypeScript offers a great feature — discriminated unions — that you can use to build such API’s. Discriminated unions, also called tagged unions, represent a finite, well-defined set of choices. source Implementing a discriminated union in TypesScript If you have a class with a then you can use that property to discriminate between union members. literal member As an example consider the union of a and , here we have a member that exists on both union members and is of a particular : Square Rectangle kind literal type source Designing the API The Chat API will receive requests from chat users and return appropriate responses. The chat users will issue the following requests: Logon Logoff SendMessage RequestNotification (request for notification of events in the chat room) The server in turn will respond with one of the following notifications: LoggedOnUsers (a list of users who available for chat, provided at logon time) UserJoined (notification that a new user has joined the chat) UserLeft (notification that a user has left the chat) MessageFrom Nothing (when the user log’s off there is nothing more to say) The definition of the request model in TypeScript is as follows … and likewise for the response Thus, in a few lines of code I have described all the cases that the Chat API needs to handle. I can then use a switch statement to handle every case as required. The default clause in the switch ensures that we have handled all possible request types. If I extend the API in the compiler will ensure that I’ve handled the new cases. This is a fantastic way to future proof against bugs. future Thanks for reading and if you found this article helpful, please hit the 👏 button and share the article, so that others can find it easily. Cheers.