I am getting the following error when trying to use Typescript with a React Native Flat List:
Type '(item: navigationTypes) => JSX.Element' is not assignable to type 'ListRenderItem<unknown>'.
Here is my code:
type navigationTypes = {
name: string
href: string
}
const navigation = [
{ name: 'Support', href: '/support' },
{ name: 'Privacy Policy', href: '/privacy-policy' },
{ name: 'Terms Of Use', href: '/terms-of-use' },
{ name: 'Terms & Conditions', href: '/terms-&-conditions' },
]
const Item = ({ title = '', href = '' }) => (
<View>
<Text>
<TextLink href={href}>{title}</TextLink>
</Text>
</View>
)
const renderItem = (item: navigationTypes) => (
<Item title={item.name} href={item.href} />
)
<View>
<FlatList
horizontal
data={navigation}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
</View>
I’m new to Typescript so I’m struggling to understand why there is an issue here.
2
Answers
The item is passed as the
item
property of an object to therenderItem
function. Which means that your function signature is not correct.If you wrote it inline, it would look like
or
const obj = { a: 1, b: 2 };
const { a, b } = obj;
const renderItem = {(dataItem.item: navigationTypes) =>
to avoid this we destructure our object like this.
{item} = dataItem;
we are destructuring the items passed to the renderItem function, and navigationTypes is its type.
const renderItem = {({item}: navigationTypes) =>
( <Item title={item.name} href={item.href} /> )}