Error: The attribute 'title' is not found in the specified type

After analyzing 23 lines of code, I encountered an issue with the message 'Property 'title' does not exist on type 'faceProductList | faceProductList[]'. How can this error be resolved?

Check out the code here

interface faceProductList {

  readonly title: string;
  readonly price: string;
  readonly prodState: string;
  readonly shipping: string;
  readonly sold: string;
  readonly src: string;
  readonly id: string;
  readonly to: string;
}

class Server {
    private url: string = 'https://foo0022.firebaseio.com/';
    public async request(id: string): Promise<(faceProductList[] | faceProductList)[]> {
        const res = await fetch(`${this.url}${id}`);
        const resArr: (faceProductList[] | faceProductList)[]  = await res.json();
        return resArr;
    }
    public async handler(id: string, valueSearch: string) { 
        await this.request(id)
        .then((array) => { 
            if(id){ 
              return  array.filter(({title}) => title.includes(valueSearch))
            }

            })
    }
}

Answer №1

When you make a request, it will give you back a

(faceProductList[] | faceProductList)[]
. This means that each item in the array is either a single faceProductList or an array of faceProductList. The error message indicates that the filter won't work if the item being filtered is an array.

If you need to meet specific requirements, you may need to flatten the result set before applying the filter:

return array
  .reduce((acc: faceProductList[], cur) => (Array.isArray(cur) ? acc.concat(cur) : acc.push(cur), acc), [])
  .filter(({ title }) => title.includes(valueSearch))

Note: Another option is to use the built-in flat method, but refer to this answer.

Alternatively, you could adapt your filter condition to handle both scenarios:

return array
  .filter((item) => Array.isArray(item)
    ? item.some(({ title }) => title.includes(valueSearch))
    : item.title.includes(valueSearch))

To make this code cleaner, flatten the array first and store it in a separate variable:

const flatArray = array.reduce((acc: faceProductList[], cur) => (Array.isArray(cur) ? acc.concat(cur) : acc.push(cur), acc), []);
if (id) {
  return flatArray.filter(({ title }) => title.includes(valueSearch));
}

return flatArray;

Answer №2

Indeed, it is a valid point -- the value

(faceProductList[] | faceProductList)[]
which - when expanded in filter - could be an element or an array of elements does not necessarily contain a title property. My recommendation is to ensure that request always produces an array. Verify the output from firebase to determine if it is a single element; if so, convert it into an array and return that instead. Adjust your signatures accordingly to meet expectations.

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

Guide on generating a video thumbnail using JavaScript Application

Searching for a way to easily create a thumbnail from a video for uploading alongside the video itself to a server? I've been looking for JavaScript libraries to simplify the process without much luck. The scenario involves the user selecting a video ...

Converting Object-Oriented Programming to Functional Programming in JavaScript

My JavaScript code looks like this: function stringFormatter(locale) { return { getA: function() { return 'A' + locale; }, getB: function() { return 'B' + locale; }, getC: function() { return &apo ...

Angular Signals: How can we effectively prompt a data fetch when the input Signals undergo a change in value?

As I delve into learning and utilizing Signals within Angular, I find it to be quite exhilarating. However, I have encountered some challenges in certain scenarios. I am struggling to come up with an effective approach when dealing with a component that ha ...

Implementing a delay for triggering an event in Angular based on certain conditions

I'm trying to create a div that triggers a click event. When the user clicks on the "click here" label, I want an alert to appear based on two conditions: first, if getListData is true, and second, only if the label is clicked after 5 seconds of getLi ...

The code in the Node.js/Express application remains unchanged even after making alterations to the source code

I apologize for the unorthodox title of this question. I struggled to find a concise way to describe my current issue. As a beginner in Node.js, I am attempting to create a simple node/express app. Initially, everything was going smoothly as I set up var ...

The type 'Application Record' is lacking these specific properties: string, any init, defaultConfiguration, and engine

I am encountering an error while running my TypeScript project: yarn build yarn run v1.22.22 $ tsc && tsc-alias src/index.ts:22:23 - error TS2769: No overload matches this call. The last overload gave the following error. Argument of type &ap ...

The properties required for type 'never[]' are not present

The type 'never[]' does not have the necessary properties from type '{ login: string; id: number; node_id: string; avatar_url: string; url: string; }': login, id, node_id, avatar_url, url When working on a component that takes an ApiUr ...

Developing typeScript code that can be easily translated and optimized for various web browsers

Can TypeScript alleviate the worry of having to use code such as this (especially when considering browsers like IE that may not support indexOf)? arrValues.indexOf('Sam') > -1 Does the transpiling process in TypeScript generate JavaScript c ...

Transferring information between Puppeteer and a Vue JS Component

When my app's data flow starts with a backend API request that triggers a Vue component using puppeteer, is there a way to transfer that data from Backend (express) to the vue component without requiring the Vue component to make an additional backend ...

Guide on enabling a new property within an Interface containing a nested array

Within my interface, there is a property named data which contains an array. The structure looks like this: type Data = { prop1: string; prop2: string }[]; interface MyInterface { prop1: string; data: Data; } Now, I have an RxJS stream where the typ ...

Error encountered while attempting to inject a store into a React application using Typescript

Currently, I am working on building a React app with TypeScript and using Redux for state management. However, I encountered an error related to the app component. https://i.sstatic.net/zetyR.png -app.tsx import React from 'react'; import { Pro ...

Reduce the size of the JSON file located in the Assets folder during an Angular build

What is the most effective method to compress JSON files in an Angular production build? I currently have a JSON file in the assets folder that remains unchanged when the production build is completed. During development, the file appears as the Developme ...

Deactivating AngularJS debug information in a gulp / typescript production compilation

What is the most effective approach to disabling debug data in a gulp production build? The recommended method for disabling debug data is: myApp.config(['$compileProvider', function ($compileProvider) { $compileProvider.debugInfoEnabled(false ...

Jasmine has detected an undefined dependency

Testing out the following code: constructor(drawingService: DrawingService) { super(drawingService); //... } private writeOnCanvas(): void { this.drawingService.clearCanvas(this.drawingService.previewCtx); this.drawing ...

What could be causing the error that pops up every time I attempt to execute a git push

When I executed the following command in git git push origin <the-name-of-my-branch> I encountered the following warning message Warning: The no-use-before-declare rule is deprecated since TypeScript 2.9. Please utilize the built-in compiler check ...

The Vue $refs Object is classified as 'unidentified' in nature

I'm encountering an issue while attempting to utilize $refs in my Vue 3 application. Each time I try, I receive the Typescript error stating that "Object is of type 'unknown'". I am uncertain about how to resolve this problem. Here's ...

Converting JSON to TypeScript with serialization and deserialization

I'm currently working on serializing TypeScript objects to JSON and vice versa. During this process, certain fields need to be transformed, such as converting `Date` objects to ISO 8601 strings and mapping enumerations to values required by the wire f ...

How can I combine my two ngIf conditions into an ngIf else statement?

Having trouble incorporating an *ngIf else with two large <div> elements, as the content seems overwhelming to organize properly while following the documentation. Initially believed that using the same styling for two open text boxes, with one hidd ...

Code Error: The type '{}' is missing the property 'mapType'

I'm currently following a tutorial on YouTube about integrating Google Maps into Ionic. I encountered an error that I'm struggling to understand. Whenever I try to run the app, I receive the following error: Check out the tutorial video here: ht ...

Unidentified action type in Vuex: RawHTML being used in a TypeScript-powered VueJS application

Whenever I try to dispatch an action on a component, I keep getting the error '[vuex] unknown action type: RawHTML'. This issue is usually related to incorrectly namespaced modules, but in this case, I am not using any modules. store/index.ts ...