Functional TypeScript: Either vs Validation

gcanti
1 min readJun 17, 2017

--

Adapted from A Tale of 3 Nightclubs

Act Zero: 10:15 Saturday Night

In which we will see how to use the type system to handle failure with the Either type and the Validation type.

Here we define some checks that all nightclubs make.

The checks can be specialised by providing a function that creates the error case. For Either this is left and for Validation this is failure.

Act One

First we can perform some checks using the monadic chain methods.

In fp-ts the Validation type does not implement the Monad class required for chaining but we can use the Either type with Left signifying failure.

Because we are using Monad the checks are fail-fast. That is, any failed check shortcircuits subsequent checks so even though we are returning the error as an Array<String> we will only ever get one error.

Act Two

An ideal nightclub would instead tell us everything that is wrong.

Applicative functors and Validation to the rescue!

This time we can use the Validation type to accumulate all errors via a Semigroup structure such as Array.

Act Three

As you can see above, collecting results from a large number of checks can get messy.

To make a large number of checks we can traverse over the checks.

--

--