有一个接口
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)
构造函数
new Date不能接受undefined,但res.date它是 typeDate | undefined,这会阻止它直接传递给构造函数。要在分配前检查,您可以使用逻辑运算符
&&或三元运算符。检查本身可以放在对象文字之前,您可以使用通常的检查
if:或直接在对象文字中