TypeScript React Native Flatlist: How to give renderItem the correct type of it's item?

J. Hesters picture J. Hesters · Oct 8, 2018 · Viewed 14.6k times · Source

I'm building a React Native app with TypeScript. renderItem complains that the destructured item implicitly has an any type. I googled and found this question and tried to implement what they teach here combined with the types in index.d.ts of the @types package for React Native.

export interface Props {
  emotions: Emotion[];
}

class EmotionsPicker extends PureComponent<Props> {
  keyExtractor = (item, index) => index;
  renderItem = ({ item }) => (
    <ListItem title={item.name} checkmark={item.checked} />
  );

  render() {
    return (
      <FlatList<Emotion>
        keyExtractor={this.keyExtractor}
        renderItem={this.renderItem}
        data={this.props.emotions}
      />
    );
  }
}

Unfortunately this does not work. How can I give item the type Emotion?

Answer

J. Hesters picture J. Hesters · Oct 8, 2018

I found a solution (though I don't know if it's ideal):

renderItem = ({ item }: { item: Emotion }) => (
  <ListItem title={item.name} checkmark={item.chosen} />
);