M
M
miliko mikoyan2019-02-27 09:25:01
typescript
miliko mikoyan, 2019-02-27 09:25:01

Property 'title' does not exist on type, Argument of type?

i wrote code that can get 2 types of array from server but i get error 23.25 lines I get two Errors The 'title' property does not exist for the type and the type argument faceProductList[][] code

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))
            }else{
                return [].concat(...array)
            }

            })
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2019-02-27
@miliko0022

Because this.request(id) returns either faceProductList[][] or faceProductList[].
And array.filter(({title}) => title.includes(valueSearch)) uniquely treats the data as faceProductList[] and doesn't take into account faceProductList[][].
Can do

public async handler(id: string, valueSearch: string) { 
        await this.request(id)
          .then((array: faceProductList[]) => { 
            ...

for the error to go away.
But the problem of ambiguity will remain and one day it will come out as a bug.
If I were you, I would do something like this:
public async request(id: string): Promise<faceProductList[][]> {
  const res = await fetch(`${this.url}${id}`);
  const resArr: faceProductList[] | faceProductList[][]  = await res.json();
  if (resArr.length === 0) {
    return resArr;
  }

  if (Array.isArray(resArr[0])) {
    return resArr;
  }

  return [resArr];
}

I can not guarantee that it will work right away, you may have to file it. But the direction of thought must be clear.
The advantage of this approach is that you will be spared from checking for "what exactly did request return, faceProductList[] or faceProductList[][] ?" with every sneeze.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question