using discriminated unions to limit cardinality

2021-01-29

 | 

~2 min read

 | 

244 words

I’ve been working on improving my understanding of data modeling lately. While reading a review of Elm, I found something click for me when I got to “Making impossible states impossible”. It was as if I felt the full weight of discriminated unions - or perhaps more accurately, my current understanding of their full weight.

What do I mean? Well, let’s consider the HTTP request. The request’s state is either loading, successful or error (for the sake of this demonstration, I’ll be ignoring the actual contents of the response).

A naive approach to modeling the request would be:

type HttpState = {
  loading: boolean
  error?: any
  success?: any
}

In this world HttpState has eight possible states. This is referred to as the cardinality and is a result of the fact that loading may be true or false while error and success may or may not be present.

In reality, however, these are expected to be mutually exclusive states (you can’t both be in error and success or loading and error).

The way to resolve this issue is to have a discriminated union:

type Loading = boolean
type HttpError = any
type HttpSuccess = any

type DiscriminatedHttpState = Loading | HttpSuccess | HttpError

In this way, we now have only three possible states (and they’d be exclusive if HttpError / HttpSuccess weren’t modeled lazily as any for demonstration purposes). That is, the cardinality is 3, which is what we intended!


Related Posts
  • 2021 Daily Journal
  • React: Discriminated Unions And Semantic Composability


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!