Error No overload matches this call TS2769

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

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)

Ответы (1 шт):

Автор решения: Grundy

конструктор 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)
→ Ссылка