Redux Connected Higher-Order React Component using TypeScript 👨🍳
While working on a feature-toggling system that allows users to switch preview features on and off, I wanted to create a featureAware
enhancer-type HOC that I could use to wrap existing enhancers, e.g. withRouter
& connect
:
I also wanted this enhancer to work on it's own:
In this case the HOC is used to inject a hasFeature
function into enhanced components:
This application already used Redux, and the selected feature-toggles were being persisted to the server. I wanted feature-toggle updates to instantly show or hide features in the application.
Components using the featureAware
enhancer HOC can use the hasFeature
function to allow conditional feature-toggle based behaviour.
After a bit of work with types, taking inspiration from withRouter
, I created the following HOC that can be used either on it's own or by wrapping other enhancers. It also allows pass-through of component-level props (like ownProps
in Redux connect
):
I briefly tried, but couldn't seem to avoid that ugly unknown
props cast or the cast to React.Component
. It works nicely however, the casts don't prevent the correct types from being inferred when using the component.