键入 React HOC 的正确方法是什么?

What is the correct way to type a React HOC?

我想弄清楚我是否正确输入了我的 React 高阶组件。在大多数情况下,这是正常工作的,但是在将 React 引用应用于 HOC 实例时,我 运行 遇到了打字问题。下面是一个简化的重现:

import * as React from "react";

// Is returning a React.ComponentClass correct here?
function HOC(): (Component: React.ComponentType) => React.ComponentClass {
    return function(Component: React.ComponentType): React.ComponentClass {
        return class Bar extends React.Component {}
    }
}

class Foo extends React.Component<{},{}> {}
const Bar = HOC()(Foo);

class Test extends React.Component {
    private ref: React.RefObject<typeof Bar> = React.createRef<typeof Bar>();

    render(): any {
        return (
            <React.Fragment>
              <Bar
                ref={this.ref} // error here
              />
            </React.Fragment>
        );
    }
}

我也在这里捕获了这个问题:https://stackblitz.com/edit/react-ts-rtmfwr

我得到的错误是:

index.tsx:20:21 - error TS2322: Type 'RefObject<ComponentClass<{}, any>>' is not assignable to type 'Ref<Component<{}, any, any>>'.
  Type 'RefObject<ComponentClass<{}, any>>' is not assignable to type 'RefObject<Component<{}, any, any>>'.
    Type 'ComponentClass<{}, any>' is not assignable to type 'Component<{}, any, any>'.
      Property 'setState' is missing in type 'ComponentClass<{}, any>'.

这应该有效:

import * as React from "react";

// In a more realistic example, there would be a more interesting relationship
// between the props types of the wrapped and resulting components.    
function HOC(): <P>(Component: React.ComponentType<P>) => React.ComponentClass<{}> {
    return function<P>(Component: React.ComponentType<P>): React.ComponentClass<{}> {
        return class Bar extends React.Component<{}> {}
    }
}

class Foo extends React.Component<{x: string},{}> {}
const Bar = HOC()(Foo);
// Get the instance type corresponding to the `Bar` constructor function,
// as you would have if you had just written `class Bar`.
type Bar = InstanceType<typeof Bar>;

class Test extends React.Component {
    private ref: React.RefObject<Bar> = React.createRef<Bar>();

    render(): any {
        return (
            <React.Fragment>
              <Bar
                ref={this.ref}
              />
            </React.Fragment>
        );
    }
}