Flow tips and tricks, part 6: Result type

NGUYEN Trung
2 min readJun 11, 2018

--

According to Wikipedia:

In functional programming, a result type is a Monadic type holding a returned value or an error code. They provide an elegant way of handling errors, without resorting to exception handling; when a function that may fail returns a result type, the programmer is forced to consider success or failure paths, before getting access to the expected result; this eliminates the possibility of an erroneous programmer assumption.

Unfortunately this isn’t a default feature of JavaScript (which wasn’t originally designed to be functional) and it becomes a very common pattern for developers to implement in the language.

With Flow it becomes easy to represent a simple result type by using disjoint union type and generic type. We can try to have a common property inside each success/error type to make the pattern matching easier.

I think it is enough with these three types for all cases we need to handle. But having to build objects for these types all the times might be painful. We can have some default builder functions to handle that:

Sometimes in practice, we could have a result that is composed of several possibilities, so don’t get limited by a boolean as discriminant attribute (like ok above), we could use another attribute named type or whatever we like as name, with specific string value to represent each possibility we have.

--

--