【问题标题】:Property 'toDate' does not exist on type 'Date' Angular firestore类型“日期”Angular Firestore 上不存在属性“toDate”
【发布时间】:2020-09-06 10:22:40
【问题描述】:

我正在尝试使用 toDate() 在 TypeScript 中将 timestamp 对象从 Firestore 转换为 Date 对象。

import { AngularFirestore } from '@angular/fire/firestore';
...
constructor(private database?: AngularFirestore) {...}
...
const someVariable = a.date.toDate();

虽然该功能在开发模式下运行良好,但我收到 TypeScript 编译检查错误。此外,由于此错误,我无法构建 prod 版本(使用 ng prod)。

a.date.toDate() ~~~~ src/app/project/some.service.ts:74:36 -
错误 TS2339:“日期”类型上不存在属性“toDate”。

有什么建议可以解决这个问题吗?

【问题讨论】:

  • 这里 a.date 是 {seconds: <sec>, nanoseconds: <nanosec>} 形式的 Firestore 时间戳。根据文档转换时间戳对象,我们需要调用toDate() 方法,这就是我正在做的......
  • "...在开发模式下工作正常..." 你不是在“开发模式”下使用 TypeScript 吗?在开发中使用它是它的基本目的。

标签: angular typescript timestamp angularfire


【解决方案1】:

toDate() 不适用于日期、字符串、数字等。将您的 date 类型更改为 any 以获得时间戳。

date: any;

顺便说一句,我通常会在 html 文件中使用 toDate()。它会显示错误但可以编译。键入 any 也将清除 html 错误。

【讨论】:

  • 但是 Firebase 提供的官方日期数据类型是什么?
  • 默认类型会产生错误,问题是关于它。如果您使用 Timestamp(需要从 Firebase 导入),可能效果很好。
【解决方案2】:

错误告诉你,据 TypeScript 所知,a.date已经Date,而不是Timestamp。因此,您需要查看 a 的类型信息。如果它说它的date 属性是Date 而实际上它是Timestamp,这就是你需要解决的问题。 (或者,当然,如果a.date 已经是Date,则不需要toDate 调用它。但是您说此代码“在开发模式下工作”,这表明它实际上是Timestamp。 )

【讨论】:

  • 没有。这里a.datea date: t {seconds: 1598898600, nanoseconds: 0}形式的firestore时间戳对象
  • 那么有一个错误让 TypeScript 相信它是一个Date!也许您的模型的类型定义与现实不符。作为 T.J. Crowder 说:“所以你需要查看 a 的类型信息。如果说它的 date 属性是 Date 而实际上它是 Timestamp,这就是你需要的修复。"
  • @KinleyChristian - 再次:"...据 TypeScript 所知,a.date 已经是 Date...您需要查看 @987654340 的类型信息@ 是...” 因为 TypeScript 清楚地认为它是 Date,而不是 Timestamp
猜你喜欢
  • 2020-05-01
  • 2018-07-12
  • 2018-05-01
  • 2020-10-07
  • 2019-12-20
  • 1970-01-01
  • 2022-07-23
  • 2023-03-18
  • 2020-10-06
相关资源
最近更新 更多