A
A
Andrey2019-09-22 12:26:09
React
Andrey, 2019-09-22 12:26:09

How to use generics in Flow inside a React component object?

The code:

/* @flow */
import * as React from 'react';

type Props<T> = {
    items: Array<T>
};
type State<T> = {
    selectedItems: Array<T>
};

class MyComponent<T> extends React.Component<Props<T>, State<T>> {
    state = {
        selectedItems: []
    };

    renderListItem = ({ item }: { item: T }) => {
        return item;
    };

  render() {
      const {items} = this.props;
      const renderedItems = items.map((item) => this.renderListItem({ item }))
      return null;
  }
}

Link to the sandbox.
Description.
Data can be passed to my component in the form of an array of objects T. The component saves part of this data in the state as an array of objects T.
Accordingly, I type Props and State types with a generic name.
Two problems arise at once:
1) State is typed T , but what is it is a new variable, it does not understand what type it is, although the neighboring Props understands that T is the type that the class is typed with. How, then, to type the state and props with the same type at the same time?
2) In the renderListItem method, as I understand it, there is also no generic T, the flow asks to type the argument, but T cannot be used. Then how to type it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-09-22
@f-end

state: State<T> = {
  selectedItems: []
}

renderListItem: ({ item: T }) => T = ({ item }) => {
  return item;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question