Member-only story

Flow’s best kept secret

Forbes Lindesay
4 min readFeb 6, 2017

--

One of the features I most often turn to when I’m frustrated by flow’s errors is covariance. That sounds scary (I think this is why it’s not more widely known about) but covariance is actually just a fancy word for read-only. I’ll use the word read-only from now on, so you can forget all about that silly word.

Although it’s much less commonly used (in my experience), contravariance can also be useful. Contravariance is just a fancy word for write-only, so from now on I’ll just call it write-only.

Read Only Properties

Lets consider an example of where you need to mark something as read-only in order for your JavaScript code to type check properly. The following code works fine, even if it is a little contrived:

// @flowfunction logStringContainer(container: {value: string}) {
logNullableStringContainer(container);
}
function logNullableStringContainer(container: {value: ?string}) {
if (container.value != null) {
console.log(container.value);
}
}
logStringContainer({value: 'foo'});

Despite it working fine, flow will give us the following error:

example.js:44:   logNullableStringContainer(container);
^^^^^^^^^
object type. This type is incompatible with the expected param
type of
7: function logNullableStringContainer(container: {value: ?string})…

--

--

Forbes Lindesay
Forbes Lindesay

Written by Forbes Lindesay

JavaScript enthusiast and maintainer of many open source projects.

Responses (3)