Enforcing Method Presence in React Components with Flow
Recently I was onFlow’s Gitterwhen someone asked the following question:
How can I type that I want a function argument to be a React component withfooBarstatic method on it?
This question made me remember that a couple months ago, I’d had a similar problem (albeit without thestaticrequirement). I’ll explain how to ensure the method is present when composing higher order components, but expect that you know how to type generic HOCs as described inthe Flow documentation.
Essentially, the main idea is to create an interface that contains the method you want to have and join it with the component passed into the function that generates the HOC.
Basically, this says, “Give me a class that’s a React component that also has an instance method called enforcedMethodand I’ll give you back a React component with the same props and state types.”
As a more complete example, suppose we wanted to build a higher-order component that fired the onClickedOutsidemethod of a component when the user clicks anywhere outside the resulting element. It would be pretty catastrophic if we applied our HOC to a component that didn’t have anonClickedOutside, so we’ll make Flow warn us if it isn’t present.
With this HOC, we can make a component set something within its state or take some other action when we click outside, and Flow will warn us if we don’t tell the HOC what to do when we click outside the element!
Now, let’s turn back to the original question of how to enforce a static method on a component. One would think that it would be as simple as addingstaticto the interface, but you and I know better. Luckily, all we need to do is tell Flow that our function expects a class that is a React component that has a callable signature.
You’ll note that all we had to change from our first example was moving the type union outside of the Class<...>expression. Now Flow will enforce that we pass in something with astatic enforceMethod!
If you need a suite cloud monitoring tools that install quickly and integrate was AWS services, you should take a look at what we are working on.