Sven Lombaert
Sven Lombaert

Reputation: 85

Flowtype: Typehinting class based HOC component

I'm trying to typehint a HOC that adds a certain prop to a passed Component, like this:

// @flow
import React, { Component } from 'react';
import type { ComponentType } from 'react';

type Props = {
  x: string,
}

const withReferral = <PassedProps: {}>(
    WrappedComponent: ComponentType<PassedProps>
): ComponentType<$Diff<PassedProps, Props>> => {
  class withReferral extends Component<PassedProps> {
    render() {
      return (<WrappedComponent {...this.props} x={'test'} />);
    }
  }

  return withReferral;
};

export default withReferral;

The error I get is this: "Cannot return withReferral because a callable signature is missing in statics of withReferral [1] but exists in React.StatelessFunctionalComponent [2]."

With [1] referencing to return withReferral and [2] referencing to a React definition: React$StatelessFunctionalComponent<Props>

Anyone that has any help?

Upvotes: 2

Views: 714

Answers (1)

Dave Meehan
Dave Meehan

Reputation: 3201

You are missing that the type of x needs to be potentially missing from the WrappedComponents props. As noted in the Flow HOC docs, the type of the injected property needs to be a union with void e.g. x: string | void.

// @flow
import React, { Component } from 'react';
import type { ComponentType } from 'react';

type Props = {
  x: string | void,    // <<== HERE
}

const withReferral = <PassedProps: {}>(
    WrappedComponent: ComponentType<PassedProps>
): ComponentType<$Diff<PassedProps, Props>> => {
  class withReferral extends Component<PassedProps> {
    render() {
      return (<WrappedComponent {...this.props} x={'test'} />);
    }
  }

  return withReferral;
};

export default withReferral;

(Try)

Upvotes: 5

Related Questions