【问题标题】:Error No overload matches this call TS2769错误没有重载匹配此调用 TS2769
【发布时间】:2021-11-22 18:39:25
【问题描述】:

有接口

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)

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    如果res.date 未定义,则取决于您希望date 成为什么。

    可能是

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

    【讨论】:

      【解决方案2】:

      假设date 应该是undefined,如果res.date 是undefined,你应该这样修复。

        date: res?.date == null ? undefined : new Date(res.date)
      

      【讨论】:

      • 所以它给出了错误“TS2551:'产品'类型上不存在属性'日期'。你的意思是'日期'吗?”
      • 是的,我已经确定了答案。
      【解决方案3】:

      简单地做:

      date: res?.date?.toDate()
      

      【讨论】:

      • 所以它给出了错误“T2339:'Product'类型上不存在属性'数据'。”
      • 这是一个错字。放置日期而不是数据
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 2021-01-26
      相关资源
      最近更新 更多