I was recently adding Flow typing to a HoC and ran into a specific use case. The HoC injected its own function into the child component while also using of the of child props in the injected method. So here's how to properly flow type it so that consumer of the HoC will enforce the typing of the child.
First, add the type for the prop you will be injecting into the child
1 2 3 |
type InjectedProps = { myInjectedMethod: () => void }; |
1 2 3 |
type OwnProps = { videoId: number }; |
1 2 3 4 5 |
function myHOC <PassedProps: {} & OwnProps>( WrappedComponent: React.ComponentType<PassedProps> ): React.ComponentType<$Diff<PassedProps, InjectedProps>> { class Wrapper extends React.Component<PassedProps> { |
Here's what each of those lines is doing:
This is ensuring that for the calling of this HoC, we enforce the typing of the child and add the requirement for our own props.
1 |
function myHOC <PassedProps: {} & OwnProps>( |
1 |
WrappedComponent: React.ComponentType<PassedProps> |
1 |
): React.ComponentType<$Diff<PassedProps, InjectedProps>> { |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// @flow const React = require('react'); type InjectedProps = { myInjectedMethod: () => void }; type OwnProps = { videoId: number }; function myHOC <PassedProps: {} & OwnProps>( WrappedComponent: React.ComponentType<PassedProps> ): React.ComponentType<$Diff<PassedProps, InjectedProps>> { class Wrapper extends React.Component<PassedProps> { myInjectedMethod() { const {videoId} = this.props; //... use videoID here } render() { return <WrappedComponent myInjectedMethod={this.myInjectedMethod} {...this.props} />; } } return Wrapper; } module.exports = myHOC; |