Why union is your best friend in modeling types in TypeScript?

Bartek Witczak
2 min readMay 28, 2019

--

One of the misconceptions about using TypeScript is lack of knowledge on how to structure data. Today let’s take a look at union types and how that can help us improve data modeling.

Imagine we have an endpoint for searching for coaches. It can either return response data with coaches, possible filters and info data or restrictions that search is impossible. JS provides dynamic data structures and apart from primitive types like Number or Boolean, everything is just an object. Our response object looks like this:

Part handling response looks like this:

Since everyone says that TypeScript is just a superset of JS. We quickly add types. Since our object can be either restriction or response, everything can be optional. Immediately we go with the simplest solution:

And this is really, really, really bad solution. 😱

Photo by Michael Mroczek on Unsplash

What can we reason from that type? Everything is optional. How IDE is going to improve our work? We’ll need to add undefined checks everywhere.

And that code doesn’t work ( strictNullChecks = true ), since everything is optional.

Let’s carefully analyze our example. We have an object, which has 2 different roles and representations. It could be EITHER response with coaches OR restriction. Those are two totally different cases. Why should we create single data structure?

Let’s split those structures into 2 interfaces. The first one is the backend response. In fact, everything is returned from API and none of the fields is optional.

Secondly, a restriction interface, which only consists of a string property. That is also required.

Finally, we need a single type for our response object. In order to combine those types, we use UNION TYPE.

Now in our functions, we can use either Response, SearchResponse or Restriction. Probably in the top level function we’ll need Response to choose which object are we dealing with. However, later we could use just Restriction or SearchResponse.

Modeling data is one of the hardest element of programming. Creating a better data model helps a lot. It helps us with reasoning, implementing functions and gives clarity to our code.

--

--