首页 > 解决方案 > What is the correct way to type a React HOC?

问题描述

I'm trying to figure out if I am typing my react Higher order component correctly. For the most part this is working correctly, however I'm running into a typing issue when applying a React reference to an instance of the HOC. Below is a simplified repro:

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

I've also capture the issue here: https://stackblitz.com/edit/react-ts-rtmfwr

The error I'm getting is:

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>'.

标签: reactjstypescripttypeshigher-order-functionshigher-order-components

解决方案


This should work:

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

推荐阅读