There is an interface
export interface Product {
type?: string
id?: string
title?: string
date?: Date
}
In the service, we call the method
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 swears at the line
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'.
I understand that the compiler swears that res.date may not be defined. But I can't figure out how to insert a check into this stream
if (res && res.date)
CodePudding user response:
Depends on what you want date
to be if res.date
is undefined.
A possibility might be
date: res && res.date && new Date(res.date)
CodePudding user response:
Assuming date
should be undefined
in case res.date
is undefined
, you should fix like this.
date: res?.date == null ? undefined : new Date(res.date)
CodePudding user response:
Simply do:
date: res?.date?.toDate()