Next thing I’d like to share is how ReScript helps in making illegal states unrepresentable in our apps.
Here’s the common pattern of shaping a state in JS:
What’s wrong with this? Let’s see how it can be handled in UI:
It can be improved a bit by re-shaping this state:
But the main issue is still there: conditional dependencies between state properties. When loading === false
(or status === "ready"
) it implicitly assumes that data
is not null
. No guarantees though. Opened doors into an illegal state.
When you use Flow or TypeScript, these tools warn you that data
might be null
and you have to add all these annoying checks to calm type system down:
I look at the code above and I’m just sad.
First of all, let me introduce you to the thing called variant
.
This is type similar to enum
in TS except its parts are not strings (nor any other data type you familiar with from JS). These things called tags
(or constructors
).
Now the magic moment: every tag
can hold its own payload!
If you’re not there yet, here’s the code (mixing ReScript & JS just for clarity’s sake!):
How beautiful is that! There’s no way to get into an illegal state in this component. Everything is type safe. Combine it with “everything is an expression” in ReScript and you can use pattern matching at any point of your JSX render tree (spot switch
as a child of <Layout />
).
You know what to do.