I have TypeScript code such as the following:
interface Props<T> {}
function HOC<P>(component: React.ComponentType<P>): React.ComponentType<P> {
return component;
}
const MyClass = HOC(class MyClass<T> extends React.Component<Props<T>, {}> {});
type MyClass<T> = React.ComponentType<Props<T>>;
function render() {
return <MyClass<string> />;
}
But this doesn't work because I get the following errors on the line with MyClass<string>
:
[ts]
JSX element type 'ReactElement<any> | null' is not a constructor function for JSX elements.
Type 'null' is not assignable to type 'ElementClass'.
[ts] Expected 0 type arguments, but got 1.
If I remove the HOC and the type declaration, it compiles fine:
interface Props<T> {}
class MyClass<T> extends React.Component<Props<T>, {}> {};
function render() {
return <MyClass<string> />;
}
So my question is, assuming that I can't modify the type declaration of HOC
, how can I declare the const MyClass
(with a type MyClass<T>
if necessary) such that the first example will compile successfully?