FlowType - inject a generic type onto a React component

I have the following component

type PropTypes<T> = {
  items: T[],
  header: (item: T) => React.Element<*>,
  body: (item: T) => React.Element<*>,
}
type StateTypes<T> = {
  expandItem: ?T,
};

export default class Accordian<T> extends React.Component {
  props: PropTypes<T>;
  state: StateTypes<T>;
  setExpandItem: (expandItem: ?T) => void;

  constructor(props: PropTypes<T>) {
    super(props);
    ...
  }
}

I would really like to draw a conclusion from itemsto find out that the parameter headeris of the same type. Instead, when I initialize the component with

<Accordian
    items={list}
    header={listItem => ...}
/>

I got:

-^ React element `Accordian`
20: export default class Accordian<T> extends React.Component {
                                   ^ T. This type is incompatible with. 
See: src/App/components/Accordian/index.js:20
19:   banks: GenericBank[],
             ^^^^^^^^^^^ object type

I found a similar question for TypeScript, but I would like to know if it is possible to deduce the general type of a React props element in FlowType?

+4
source share
1 answer

Your example does not work, because in it you initialize the state of the accordion with a string.

class Accordian<T> extends React.Component<PropTypes<T>, StateTypes<T> {
    state = {
      expandItem: '1'
    };
}

A string T, T string. , T , , .

, . , items,

class Accordian<T> extends React.Component<PropTypes<T>, StateTypes<T>> {
  constructor(props) {
    super(props)
    this.setState({
      expandItem: this.props.items[0]
    });
  }
}
0

Source: https://habr.com/ru/post/1686923/


All Articles