Reputation: 2594
I want to use typescript in my brand new project but I've a hard time to type an HOC component
const withClass = (Wrapped: Component<any, {}, any>, className: string) => {
return props => (
<div className={className}>
<Wrapped />
</div>
);
};
It doesn't work with this error
Type error: Argument of type 'typeof App' is not assignable to parameter of type 'Component'. Type 'typeof App' is missing the following properties from type 'Component': context, setState, forceUpdate, render, and 3 more. TS2345
so what's the right way?
Upvotes: 3
Views: 4727
Reputation: 222309
Component<...>
type designates an instance of React.Component
.
If the intention is to provide a component itself and don't limit a HOC to class components then the right type is ComponentType
:
const withClass = (Wrapped: React.ComponentType<any>, className: string) => { ... }
It's also preferable to use specific props type instead of any
. If props should be passed to wrapped component like it's usually expected from a HOC, this issue should be addressed as well:
const withClass = <P extends {}>(Wrapped: React.ComponentType<P>, className: string) => {
return props => (
<div className={className}>
<Wrapped {...props as P} />
</div>
);
};
Upvotes: 11