miliko0022
@miliko0022
Краткие личные сведения, включая интересующую вас

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

я написал код который из сервера может получить 2 типа массива но я получаю ошибку 23.25 lines I get two Errors The 'title' property does not exist for the type and the type argument,Я ожидаю, что строки 23 типа faceProductList [] и 25 типа faceProductList [] [] код

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

            })
    }
}
  • Вопрос задан
  • 150 просмотров
Решения вопроса 1
search
@search
мама говорит что я особенный
Потому что this.request(id) возвращает или faceProductList[][] или faceProductList[].

А array.filter(({title}) => title.includes(valueSearch)) однозначно обрабатывает данные как faceProductList[] и не учитывает faceProductList[][].

Можно сделать

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

для того чтоб ошибка ушла.

Но проблема неоднозначности останется и однажды вылезет в виде бага.

На вашем месте я бы сделал как-то так:

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];
}


не могу гарантировать что это заработает сразу, возможно прийдётся подпилить. Но направление мысли должно быть понятным.

Плюс этого подхода - вы будете избавлены от проверки на "а что именно вернула request, faceProductList[] или faceProductList[][] ?" при каждом чихе.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы