I have a component MyComponent that takes in some props and one of them is optional:
type Props = {
a: string;
b: number;
c?: string;
}
I wrote a higher-order component that adds some functionality based on property c. In order for it to make sense, I decided to make property c on HOC required:
type CProps = Props & {
c: string;
};
export const withC = (WrappedComponent: ComponentType<CProps>) => {
const WithC = (props: CProps) => {
///...
}
return WithC;
};
Now, typescript is complaining when I try to do this:
const MyComponentC = withC(MyComponent);
saying that property c is required on withC but not on MyComponent.
How do I bypass this, ideally without changing the props type of MyComponent?
CodePudding user response:
type CProps = Props & {
c: string;
};
export const withC = (WrappedComponent: ComponentType<Props>) => {
const WithC = (props: CProps) => {
///...
}
return WithC;
};
WrappedComponent should not have a required c yet, but WithC should.
CodePudding user response:
WithC will always run even if you didn't pass c prop. so you have to call that function if c prop is passed
