I need to type HOC for my component (and that was asked millions of times). But I need to do something opposite to the typical withSomething injection. I need to add an extra property to my outer component and pass all other (but unknown) properties to the inner component:
// @flow
import * as React from 'react'
// That's an example of a standard component doing nothing
type Props = {| str: string, num: number |}
const Hello = ({ str, num }: Props): React.Node => {
console.log(str, num)
return <div>'Hello'</div>
}
// That's the standard (and working) example of the component with injected prop.
// It's an equivalent of prop currying, I set str prop to some default value
type InnerInjected = {| str: string |}
const withInnerInject = <P>(
Component: React.AbstractComponent<$Exact<{ ...P, ...InnerInjected }>>,
): React.AbstractComponent<P> => {
return (props: P) => {
return <Component str="aaa" {...props} />
}
}
const InnerInjectHello = withInnerInject(Hello)
// And here is non-working example.
export const withOuterInject = <P>(
Component: React.AbstractComponent<P>,
): React.AbstractComponent<P> => {
return (props: P) => {
// I need to pass the bool (or some other variable) to my component to perform
// some action with it based on its value and return the standard component with all
// that component properties that I don't know yet.
const { bool, ...rest } = props
return <Component {...rest} />
}
}
const OuterInjectHello = withOuterInject(Hello)
const Example = (): React.Node => {
return (
<>
{/* Both num and str props are set as intended */}
<Hello num={25} str="something" >
{/* str is injected with value of 'aaa' */}
<InnerInjectHello num={25} />
{/* Works, but typing is wrong */}
<OuterInjectHello str="aa" num={25} bool />
</>
)
}
I tried several $Diff<> and $Rest<> approaches but they simply don’t work with generics.