Make sure to include a warning in the renderItem prop of your Flashlist component

I have encountered a type warning in my React Native application. The warning is related to the renderItem prop of FlashList. How can I resolve this issue?

Warning:

Type 'import("/Users/mac/Desktop/project/pokeApp/node_modules/@react-native/virtualized-lists/Lists/VirtualizedList").ListRenderItem<import("/Users/mac/Desktop/project/pokeApp/api/pokeapi").Pokemon>' is not compatible with type 'import("/Users/mac/Desktop/project/pokeApp/node_modules/@shopify/flash-list/dist/FlashListProps").ListRenderItem<import("/Users/mac/Desktop/project/pokeApp/api/pokeapi").Pokemon>'. The parameters 'info' in both types are incompatible. The property 'separators' is missing in type 'import("/Users/mac/Desktop/project/pokeApp/node_modules/@shopify/flash-list/dist/FlashListProps").ListRenderItemInfo<import("/Users/mac/Desktop/project/pokeApp/api/pokeapi").Pokemon>' but it is required in type 'import("/Users/mac/Desktop/project/pokeApp/node_modules/@react-native/virtualized-lists/Lists/VirtualizedList").ListRenderItemInfo<import("/Users/mac/Desktop/project/pokeApp/api/pokeapi").Pokemon>'.ts(2322) The declaration for 'separators' is in VirtualizedList.d.ts(79, 3). The expected type is from the property 'renderItem' declared on type 'IntrinsicAttributes & IntrinsicClassAttributes<FlashList> & Pick<Readonly<FlashListProps>, "pointerEvents" | ... 171 more ... | "persistentScrollbar"> & InexactPartial<...> & InexactPartial<...>'

import { View, Text, ScrollView, TouchableOpacity, StyleSheet, Image, ActivityIndicator, ListRenderItem } from 'react-native'
import React, { useEffect, useState } from 'react'
import { Link } from 'expo-router'
import { Pokemon, getPokemon } from '@/api/pokeapi'
import { Ionicons } from '@expo/vector-icons';
import { useQuery } from '@tanstack/react-query';
import { FlashList } from "@shopify/flash-list";

const Page = () => {

    const pokemonQuery = useQuery({
        queryKey: ["pokemon"],
        queryFn: getPokemon,
        refetchOnMount: false
    })

    const renderItem: ListRenderItem<Pokemon> = ({ item }) => {
        return (
            <Link href={`/(pokemon)/${item.id}`} key={item.id} asChild>
                <TouchableOpacity>
                    <View style={styles.item}>
                        <Image source={{ uri: item.image }} style={styles.preview} />
                        <Text style={styles.itemText} >{item.name}</Text>
                        <Ionicons name='chevron-forward' size={24} />
                    </View>
                </TouchableOpacity>
            </Link>
        )
    }

    return (
        <View style={{ flex: 1 }}>
            {pokemonQuery.isLoading && <ActivityIndicator style={{ marginTop: 30 }} />}
            <FlashList
                data={pokemonQuery.data}
                renderItem={renderItem}
                ItemSeparatorComponent={() => <View style={{ height: 1, width: "100%", backgroundColor: "#dfdfdf" }} />}
                estimatedItemSize={100}
            />
        </View>
    )
}

const styles = StyleSheet.create({
    item: {
        padding: 10,
        height: 100,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center"
    },
    itemText: {
        fontSize: 18,
        textTransform: "capitalize",
        flex: 1
    },
    preview: {
        width: 100,
        height: 100
    }
})
export default Page

Answer №1

The FlashList comes with its own unique types. When dealing with the prop renderItem, which has a specific type called ListRenderItem, it's important to note that using the ListRenderItem from react-native may not work as expected for the FlashList's renderItem. Consider avoiding passing the type directly to the renderItem or try to properly type the parameters.

const renderItem = ({ item }: Pokemon) => {
  return (
    <Link href={`/(pokemon)/${item.id}`} key={item.id} asChild>
      <TouchableOpacity>
        <View style={styles.item}>
          <Image source={{ uri: item.image }} style={styles.preview} />
          <Text style={styles.itemText} >{item.name}</Text>
          <Ionicons name='chevron-forward' size={24} />
        </View>
      </TouchableOpacity>
    </Link>
  )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A TypeScript interface or class

Just had a lively discussion with a coworker and wanted to get some clarification. When shaping an object in TS, should we use a class or an interface? If I need to ensure that a function returns an object of a specific type, which one is the best choice? ...

Analyzing a sizable JSON file serving as the data source for a PostgreSQL database

Currently, I am working on a Next.js project that involves a large JSON file (~65,000 lines) serving as data for a Prisma Postgres database. The structure of the file includes entries like the following: [ { "NativeClass": "class-name", "Classes" ...

Issue "Value of type '{}' cannot be assigned to parameter of type 'T | (() => T)'" encountered within a React component containing a type parameter

Currently, I am attempting to achieve the following: function SomeComponent<T>({ children }: PropsType) { const [configuration, setConfiguration] = useState<T>({}) } However, I am encountering this issue: The argument of type '{}&apos ...

Differences between Typescript Import and JavaScript import

/module/c.js, attempting to export name and age. export const name = 'string1'; export const age = 43; In b.ts, I'm trying to import the variables name and age from this .ts file import { name, age } from "./module/c"; console.log(name, ...

Is there a way to include the request body (req.body) in the msg object using express-winston?

My current challenge involves logging {{ req.body }} using the msg: object in express-winston. Even after whitelisting the body with expressWinston.requestWhitelist.push('body');, it still does not appear in the log. export const accessLogger = ...

What is the best way to organize the Firebase data that is stored under the user's unique

Hey there, I'm currently working on developing a leaderboard feature for an app. The idea is that users will be able to store their "points" in a Firebase database, linked to their unique user ID. This is how the data is structured in JSON format: ...

Prevent the event listener from continuously triggering

I have a situation where every time I create an Angular component, an event listener is added. However, upon leaving the page and returning to it, a new event listener is added because the constructor is called again. The problem arises when this event is ...

Learn how to create a versatile TypeScript function that combines an array parameter and values to form an object

I've created a function that combines an array of keys with an array of values to form an object. Here's how the function looks: function mergeToObject(keys: string[], values: string[]) { const object:? = {} for (let i = 0; i < keys.length ...

Mapping a JSON array within a static method in Angular2 and TypeScript

Struggling with the syntax to properly map my incoming data in a static method. The structure of my json Array is as follows: [ { "documents": [ { "title": "+1 (film)", "is-saved": false, ...

Typescript types for React Native's SectionList: A comprehensive guide

Currently, I am in the process of developing a React Native app using TypeScript. In order to display information in a structured manner, I decided to implement a SectionList. Following the official documentation, I have written the following code snippet: ...

Using object in TypeScript to reduce arrays

Is there a way to set the return value for my reducer in TypeScript? I am looking to achieve: Instead of using 'any', what should I assign as the type for acc? How can I define my return type so that the output will be {temp: 60, temp: 60}? retu ...

Display the current date in YYYY/MM/DD format using a single method in React and TypeScript

Is there a better way to retrieve YYYY/MM/DD data using just one method? I attempted the following: date = created_at // from API const sendDate = `${String((date.getMonth() + 1)).padStart(2, '0')}${String(date.getDate()).padStart(2, '0&apos ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

Steps to integrating an interface with several anonymous functions in typescript

I'm currently working on implementing the interface outlined below in typescript interface A{ (message: string, callback: CustomCallBackFunction): void; (message: string, meta: any, callback: CustomCallBackFunction): void; (message: string, ...m ...

Provide an immutable parameter to a function that will not cause any changes

Looking to develop a function named batchUsers, requiring a parameter of type readonly string in order to create a DataLoader. However, when calling the User.findBy function within my batchUsers function, it's causing issues due to conflicting paramet ...

Using Angular 6 to Share Data Among Components through Services

I am facing an issue in my home component, which is a child of the Dashboard component. The object connectedUser injected in layoutService appears to be undefined in the home component (home userID & home connectedUser in home component logs); Is there ...

What is the best way to create a memoized function in React?

I am currently developing an application using react and typescript, and I am facing a challenge in memoizing a function. const formatData = ( data: number[], gradientFill?: CanvasGradient ): Chart.ChartData => ({ labels: ["a", ...

Encountering issues in d3.js following the transition to Angular 8

After upgrading my Angular 4 app to Angular 8, I encountered an issue where the application works fine in development build but breaks in production build. Upon loading the application, the following error is displayed. Uncaught TypeError: Cannot read p ...

Using React MUI to implement a custom Theme attribute within a component

I have a CircularProgress element that I want to center, and to make the styling reusable, I decided to create a theme.d.ts file: import { Theme, ThemeOptions } from '@mui/material/styles' declare module '@mui/material/styles' { inte ...

Tips for creating a custom waitForElementText function in Playwright

I need to implement a function called waitForElementText() in playwright. For example, I have headers labeled with the CSS selector '.header-name' on each page. When navigating from the Home page to the Users page, I provide two parameters to ...