“Hands create art on a pottery wheel” by SwapnIl Dwivedi on Unsplash

Clear, clean and concise, are some of the adjectives I would associate with an API that makes for a pleasant and productive development experience.

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 literal member then you can use that property to discriminate between union members.

As an example consider the union of a Square and Rectangle, here we have a member kind that exists on both union members and is of a particular 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:

The server in turn will respond with one of the following notifications:

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 future the compiler will ensure that I’ve handled the new cases. This is a fantastic way to future proof against bugs.

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.