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

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

Guide on accessing a modal component in Angular?

I have an Edit Button on my component called SearchComponent. When the user clicks this button, it currently redirects them to another component named EditFormComponent using navigateByUrl('url-link'). However, I would like to enhance the user ex ...

How can I arrange selected options at the top in MUI autocomplete?

I am currently working with mui's useAutocomplete hook https://mui.com/material-ui/react-autocomplete/#useautocomplete Is there a way to programmatically sort options and place the selected option at the top using JavaScript sorting, without resorti ...

Strategies for obtaining the return type of a map and only including the type S

How can I retrieve the return type of map and only display S? const initialState = { x: 1, y: 2 } type InitialStateType = typeof initialState type MapGetter<S, R, R1> = { map: (state: S) => R mapB?: (state: S) => R1 // more ... } ...

A glitch was encountered during the execution of the ionic-app-scripts subprocess

I recently started using Ionic 3 and created an application that I'm trying to convert into an APK. To generate a debug (or testing) android-debug.apk file, I used the following CLI command: ionic cordova build android --prod The pages are declared ...

What are the guidelines for utilizing square brackets [ ] in directives like @Inputs?

I'm feeling a bit lost. Check out this straightforward directive: @Directive({ selector: '[myDirective]' }) export class MyDirective { private textContent: string; private isEnabled: boolean; @Input() myD ...

Arrange the columns in Angular Material Table in various directions

Is there a way to sort all columns in an Angular material table by descending order, while keeping the active column sorted in ascending order? I have been trying to achieve this using the code below: @ViewChild(MatSort) sort: MatSort; <table matSort ...

Typescript classes implementing data hydration and dehydration techniques

Exploring ways to share TypeScript classes or interfaces between a React + TS frontend and node + TS backend. Converting class instances into JSON poses a challenge as TS types are removed during compile time. Considering options for defining objects in a ...

One effective way to transfer state to a child component using function-based React

My goal is to pass an uploaded file to a child component in React. Both the parent and child components are function-based and utilize TypeScript and Material-UI. In the Parent component: import React from 'react'; import Child from './ ...

Util Deprecations resolved with TSLint Autofix

Is there a feature in VSCode that can automatically fix deprecations related to the util library? For example: if (isNullOrUndefined(this.api)) { Would be better written as: if (this.api === null || this.api === undefined) { While there isn't an ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

The return type in Typescript for dynamically generated return values

If I have a function in Typescript 2.0 like this: doSomething(): any { const apple: Apple = ... const pears: Pear[] = ... return { apple: apple, pears: pears } } I am aware that the function will always produce an object ...

Application Initialization Error: appInits is not a valid function

When my Angular v17 application starts, I need to set some important values right away. This is how it's done in app.config.ts: export const appConfig: ApplicationConfig = { providers: [ ConfigService, ... { pr ...

Tricks for preventing axios from caching in GET requests

I am utilizing axios in my React-Native application Firstly, I set up the headers function setupHeaders() { // After testing all three lines below, none of them worked axios.defaults.headers.common["Pragma"] = "no-cache"; axios.defaults.heade ...

What is the best method for implementing Datepicker translations in Angular?

I am looking to incorporate the DatePicker component in Angular, enabling users to select a date that can be translated based on their browser's settings. Any suggestions on how to achieve this? <mat-form-field appearance="fill"> ...

Is there a way to help my KafkaJS consumer stay patient while waiting for a broker to become available?

My KafkaJS consumer setup looks like this: // Create the kafka client const kafka = new Kafka({ clientId, brokers, }); // Create the consumer const consumer = this.kafka.consumer({ groupId, heartbeatInterval: 3000, sessionTimeout: 30000, }); // ...

Creating paragraph breaks or splitting objects in the Document Object Model (DOM) can be

Is there a way to extract only a specific sentence from a given example? For instance, let's say I have the following text: "Our client, a highly respected moving company is seeking a National Account Move Coordinator to join their team based rem ...

Unable to retrieve information from service using Angular 1.6 and TypeScript

I'm having an issue retrieving data from a Service in my Controller. Here is the code for my Service file: import {IHttpService} from 'Angular'; export class MyService { public static $inject = ['$http']; constructor(private $htt ...

Issue with Ionic Native File: File.writeFile function - file is not being created and there is no callback response

I've exhausted all the different solutions I could find, but unfortunately, the file isn't getting saved and nothing seems to be happening. The callback functions aren't being called - neither success nor error. Here are the solutions I&apo ...

Encountered an issue while attempting to assign a value to a property that is declared as [key in keyof T]

I am currently working on implementing a function that selects specific properties of an object. Here is the current function: const project = function<T>(object: T, projection: Projection<T>): Partial<T> { throw new Error("not imple ...