When utilizing the React HOC function, the component parameter fails type checking with the following code snippet:
import * as React from 'react';
interface FooProps {
foo: string;
bar: string;
}
function withProps<P extends FooProps>(
Comp: React.ComponentType<P>
) {
return class extends React.Component {
render() {
return <Comp foo="foo" bar="bar"/> // "Comp" fail typecheck
}
}
}
I believed that the constraint P extends FooProps
would be sufficient, but unfortunately it is not.
This error was encountered:
Type '{ foo: string; bar: string; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
Property 'foo' does not exist on type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
Interestingly, Visual Studio Code's intellisense correctly identified foo
and bar
props as FooProps.foo
and FooProps.bar
respectively, but stumbled on Comp
.
Why doesn't this function work as expected?
It seems that there might be a misunderstanding in how generic functions infer variable types.
NOTE: Utilizing
Comp: React.ComponentType<FooProps>
resolves the issue successfully.