Note that PropsInput and PropsOutput have bound of {}. (As expressed in PropsInput: {} and PropsOutput: {}.) This means that PropsInput and PropsOutput must be object types so we may treat them as such in the implementation of mapProps(). If you do not add the : {} then you would not be able to spread PropsInput or PropsOutput!

We have one last thing to do. Add a type for the mapper function which will take PropsInput and return PropsOutput for mapProps().

Flow will not require you to add type annotations, but it is a smart idea to add annotations anyway. By adding type annotations you will get better error messages when something is broken. An annotated version of a mapProps() usage would look like:

Injecting Props With a Higher-order Component

A common use case for higher-order components is to inject a prop. Like a navigation prop, or in the case of react-redux a store prop. How would one type this? Let us start with a higher-order component that does not add any new props:

Let’s look at the type for our output component. In other words the type for MyOutputComponent in const MyOutputComponent = injectProp(MyInputComponent).

React.ComponentType<$Diff<Props, { foo: number | void }>

The type of props for this component is:

$Diff<Props, { foo: number | void }>

This uses $Diff to say that the type for props is everything in Props (which is the props type for our output component) except for foo which has a type of number.

Note: If foo does not exist in Props you will get an error! $Diff<{}, { foo: number }> will be an error. To work around this use a union with void, see: $Diff<{}, { foo: number | void }>. An optional prop will not completely remove foo. $Diff<{ foo: number }, { foo?: number }> is {foo?:number} instead of {}.

Note: Remember that the generic type, Props, needs the bound {}. As in Props: {}. Otherwise you would not be able to spread Props in <Component {...props} foo={42} />.

Supporting defaultProps With React.ElementConfig<>

The higher-order-components we’ve typed so far will all make defaultProps required. To preserve the optionality of defaultProps you can use React.ElementConfig<typeof Component>. Your enhancer function will need a generic type for your component. Like this: