1

I'm trying to run a Flatlist with typescript, but it seems to allow only an expression function that has its props destructured. I cant seem to figure out how desctructure with the necessary type (Suggestion). Does anyone know how to fix this?

Unchanged flatlist function

  const renderSuggestions = () => 
         <FlatList
        data={data}
        renderItem={renderItem}
        onPress={(item:Suggestion) => handleSelect(item)}
        keyExtractor={item => item.place_id}
      />

Attempt 1 (error:renderItem overload not found)

 const renderItem = (item:Suggestion)=> (

    <View>
      <TouchableOpacity >
        <Text >{item.structured_formatting.main_text}</Text>
      </TouchableOpacity>
    </View>
  )

Attempt 2 (typescript type error (implicit any type))

const renderItem = ({item})=> (

    <View>
      <TouchableOpacity >
        <Text >{item.structured_formatting.main_text}</Text>
      </TouchableOpacity>
    </View>
  )

attempt per answer: item / index not found error

  const renderItem = (item:Suggestion, index:number)=> (

    <View>
      <TouchableOpacity >
        <Text >{item.structured_formatting.main_text}</Text>
      </TouchableOpacity>
    </View>
  )


  const renderSuggestions = () => 
         <FlatList
        data={data}
        renderItem={({ item:Suggestion, index:number }) => renderItem(item, index)}
        onPress={(item:Suggestion) => handleSelect(item)}
        keyExtractor={item => item.place_id}
      />
David Scholz
  • 8,421
  • 12
  • 19
  • 34
polar
  • 524
  • 5
  • 24
  • [David's answer](https://stackoverflow.com/a/71640184/1218980) is correct, but about how to type destructured params, here's how to do it: https://stackoverflow.com/q/53329592/1218980 – Emile Bergeron Mar 27 '22 at 21:03
  • Please, ask one question at a time. you have literally changed your whole initial question, which is answered with my answer. The question now reflects something completely different. – David Scholz Mar 27 '22 at 21:07
  • 1
    @DavidScholz removed the handleselect stuff to maintain one question – polar Mar 27 '22 at 21:08

1 Answers1

3

For a FlatList the type of the passed data prop determines the type of the destructured item. Here is a minimal working example for seeing this.

import React, { useState } from "react"
import { FlatList } from "react-native"

type DataType = {
  id: number,
  someThing: string
}
const FlatListWithType = () => {
   // we specify the type here
   const [data, setData] = useState<DataType[]>()

   return (
     <FlatList
       data={data}
       renderItem={({ item, index }) => (

       )}
     />
   )
}

The type suggestion should work now.

enter image description here

David Scholz
  • 8,421
  • 12
  • 19
  • 34