Home > Enterprise >  Desctructure in function props with typescript
Desctructure in function props with typescript

Time:03-28

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}
      />

CodePudding user response:

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

  • Related