I find many of the tutorials on fp-ts to be a bit too low level. They are great
for learning the fundamentals, but I wanted to see some more practical examples.
I've been using fp-ts in production for a while now, and I wanted to explore
some commone use cases that I've encountered.
Before jumping into the examples, I want to mention another library that I found
to be very useful. io-ts is a library for
runtime type checking. It is a great companion to fp-ts, and I will be using it
in some of the examples below.
DeepEqual of Nested Objects
Sometimes you need to compare two objects to see if they are equal. This is
pretty easy to do with primitive values, but it gets a bit more complicated when
you have nested objects. You can use JSON.stringify to compare the objects,
but this is not very efficient. It is also not very flexible, since it will
compare all of the properties on the object. What if you only want to compare
some of the properties?
Elegant IO Layer (Error Handling)
This is borrowed heavily from
fp-ts and Even More Beautiful API Calls (w/ sum types!)
but also expands on it a bit. This pattern is great for handeling APIs that are
less trustworthy. It allows you to handle errors in a very elegant way, without
having to crash the application.
Branching Render Logic
This pattern is very useful in React applications. It allows you to branch your
render logic based on the type of data that you have. This is very useful when
you have a loading or error state that you want to handle differently.
When working with repsonsiveness it can sometimes be nessisary to conditionally
return values based on the screen size. This pattern allows you to do that in a
very elegant way. While its not nessisary to use fp-ts for this, it does make it
use of functional programming concepts such as currying and composition.
This can also be done using ADTs which is a bit more elegant, but also a bit
more complicated. I've only used an ADT abstraction from
morphic-ts but dont want to add that
dependency to this project (right now).