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

时间:2018-09-18 04:04:08

标签: reactjs typescript types higher-order-functions higher-order-components

我正在尝试确定我是否正确输入了我的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>'.

1 个答案:

答案 0 :(得分:4)

这应该有效:

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>
        );
    }
}