I have a function that wraps a React component with <IntlContextProvider>
component. I want to define the GenericFunctionType
but I have no ideia what shoulb be.
const wrapIntl: GenericFunctionType = (ComponentToWrap) => {
class Wrapper extends React.PureComponent {
render() {
return (
<IntlContextProvider>
<ComponentToWrap {...this.props}/>
</IntlContextProvider>
);
}
}
return Wrapper;
}
This function wrapIntl
will be used like this:
export const TranslateText = wrapIntl(({text}: {text: string}) =>
<>
{React.useContext(IntlContext).translate(text)}
</>
)
I have this now:
interface GenericFunctionType {
<T>(ComponentToWrap: React.ReactNode): T
}
But it has this errors:
TS2322: Type '(ComponentToWrap: ReactNode) => typeof Wrapper' is not assignable to type 'WrapIntlFunctionType'. Type 'typeof Wrapper' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'typeof Wrapper'.
TS2604: JSX element type 'ComponentToWrap' does not have any construct or call signatures.
You have the right idea in making it generic. T
will be the type for the props, and you can have it accept and return a React.ComponentType<T>
:
interface GenericFunctionType {
<T,>(ComponentToWrap: React.ComponentType<T>): React.ComponentType<T>
}
Although the explicit type for it is not really necessary, you could just specify the types on the implementation (you need to anyway because you need to use T
in the Wrapper
class definition):
const wrapIntl = <T,>(ComponentToWrap: React.ComponentType<T>): React.ComponentType<T> => {
class Wrapper extends React.PureComponent<T> {
render() {
/// ....
}
}
return Wrapper;
}