TypeScript React Native Flatlist: How to give renderItem the correct type of it's item?
I found a solution (though I don't know if it's ideal):
renderItem = ({ item }: { item: Emotion }) => (
<ListItem title={item.name} checkmark={item.chosen} />
);
I know it's an old question but people googling it might still appreciate it.
import { FlatList, ListRenderItem } from 'react-native'
/*
.
.
.
*/
renderItem: ListRenderItem<Emoticon> = ({ item }) => (
<ListItem title={item.name} checkmark={item.checked} />
);
This is because at the time renderItem
is defined, TypeScript has no way of knowing it's supposed to go as the renderItem
prop of FlatList
.
If you had skipped the variable and directly plopped the function in the prop, TypeScript should be able to infer it correctly:
export interface Props {
emotions: Emotion[];
}
class EmotionsPicker extends PureComponent<Props> {
render() {
return (
<FlatList<Emotion>
keyExtractor={(item, index) => index}
renderItem={({ item }) => <ListItem title={item.name} checkmark={item.checked} />}
data={this.props.emotions}
/>
);
}
}