Flow tips and tricks, part 5: Read-only types
Problem
Suppose that we have some doSomething
method that takes an array of animals as its input, animal might be a dog that is owned by someone, or a tiger which doesn’t have any owner:
So what’s the problem with Flow, we just passed an array of dogs which are animals-compliant, why we got a so cryptic error message from Flow?
Explanation
We got an error at the end because doSomething
might mutate its input argument, pushing a Tiger
object to it for example, which would make dogs
to be no longer a list of Dog
. So we cannot substitute anArray<Animal>
by an Array<Dog>
.
Most of the time, we need to make sure that doSomething
doesn’t mutate its input argument in order to pass an Array<Dog>
safely into it. We can do that with $ReadOnlyArray
type like following:
Flow does offer another read-only type for object $ReadOnly
which make all attributes of an object read-only.
At the time of writing this article, there’s a ton of others that explain clearly what are variances (read-only or write-only) problems in Flow. I found that two of them are excellent:
I also published another article that took a deep dive into how Subtyping System works, the example above is just a particular case of this mechanism.