1

Есть интерфейс

export interface Product {
  type?: string
  id?: string
  title?: string
  date?: Date
}

В сервисе вызываем метод

  getById(id: string) {
    return this.http.get(`${environment.fbDbUrl}/products/${id}.json`)
      .pipe( map ( (res: Product) => {
        return {
          ...res,
          id,
          date: new Date(res.date)
        }
      }))
  }

IDEA ругается на строку

date: new Date(res.date)
TS2769: No overload matches this call.   Overload 1 of 4, '(value: string | number | Date): Date', gave the following error.     Argument of type 'Date | undefined' is not assignable to parameter of type 'string | number | Date'.       Type 'undefined' is not assignable to type 'string | number | Date'.   Overload 2 of 4, '(value: string | number): Date', gave the following error.     Argument of type 'Date | undefined' is not assignable to parameter of type 'string | number'.       Type 'undefined' is not assignable to type 'string | number'.

Я так понимаю, что компилятор ругается, что res.date может быть не определен. Но я не соображу как в этот стрим вставить проверку

if (res && res.date)
4
  • А почему просто не date: res.date? 22 ноя 2021 в 7:54
  • Проект учебный, поэтому исхожу из того, что было в коде у ютубера, а я только изучаю Angular. Подозреваю, что возможно значение res.date может быть number
    – alex
    22 ноя 2021 в 9:40
  • 1
    res && res.date && new Date(res.date)
    – Grundy
    22 ноя 2021 в 9:42
  • можете в виде ответа оформить, а я закрою вопрос
    – alex
    22 ноя 2021 в 9:59

1 ответ 1

2

конструктор new Date не может принимать undefined, однако res.date имеет тип Date | undefined, что не дает напрямую передать его в конструктор.

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

Саму проверку можно вынести перед литералом объекта и использовать обычный if:

.pipe( map ( (res: Product) => {
    var date = undefined;
    if (res.date){
        date = new Date(res.date);
    }
    return {

либо напрямую в литерале объекта

date: res && res.date && new Date(res.date)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.