I have a HOC that provides one property to a wrapped component.
I want to write Typescript type definitions that properly expose Props type of the component created by this HOC: basically copy (infer) type of props of the wrapped component and remove the property my HOC provided. Is it possible?
In the example below, I have a HOC withBar that provides the bar:string prop to any wrapped component that accepts it. Therefore the Foo = withBar(FooBar) component should have props FooBarProps excluding the bar, which means only {foo: string}. However Typescript still apparently thinks Foo component should also get the foo property.
I use Typescript 3.3.1.
import * as React from "react";
interface FooBarProps {
foo: string;
bar: string;
}
class FooBar extends React.PureComponent<FooBarProps> {
public render() {
return <>{this.props.foo} {this.props.bar}</>;
}
}
export function withBar<TProps>(
WrappedComponent: React.ComponentType<TProps & {bar: string}>
) {
return class WithBar extends React.PureComponent<TProps> {
public render() {
return <WrappedComponent
{...this.props}
bar={"BAR"}
/>;
}
};
}
const Foo = withBar(FooBar);
// Typescript complains here:
// Error:(29, 14) TS2741: Property 'bar' is missing in type
// '{ foo: string; }' but required in type 'Readonly<FooBarProps>'.
const foo = <Foo foo="FOO" />;