I am new to Typescript and I cannot figure out how to correctly type HOC with it. I already spent all day to figure it out without any success. I am having very basic code snippet with BaseComponent and one simple HOC. For some reason, when creating the BaseComponent, I am getting Typescript error:
Type '{ total: number; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{ children?: ReactNode; }> & Readonly<...>'. Property 'total' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{ children?: ReactNode; }> & Readonly<...>'.
Any idea how to correctly set up Prop types?
BaseComponent:
interface SummaryProps {
sum: number;
}
class Summary extends React.Component<SummaryProps> {
render() {
return (
<div>{this.props.sum}</div>
);
}
}
export default withMyHOC(Summary);
HOC:
interface WithMyHOCProps {
total: number;
}
const withMyHOC = (WrappedComponent: React.ComponentType<any>): React.ComponentClass => {
return class extends React.Component<WithMyHOCProps> {
render() {
return (
<WrappedComponent
{...this.props}
sum={this.props.total + 1}
/>
);
}
};
};
export default withMyHOC;
Initialization:
import Summary from 'features/Summary.tsx';
<Summary total={5} /> // here I am getting Typescript error described above
By passing
{...this.props}, you are passing all the props ofwithMyHOCto the underlying component as well. This includestotalas well, butSummarydoes not have the prop 'total'.So oyu need to add all props to the child as well.