Firebase 如何在TypeScript数据模型中使用FieldValue ServerTimestamp?

Firebase 如何在TypeScript数据模型中使用FieldValue ServerTimestamp?,firebase,google-cloud-firestore,Firebase,Google Cloud Firestore,我正在使用TypeScript为Firebase中的文档定义数据模型。创建文档时,createdOn字段将是服务器时间戳sentinal,否则它是日期。例如 export interface Post<MODE extends 'create' | 'read'> { comment: string; createdOn: MODE extends 'create' ? FieldValue : Date; } 然后当我使用它时,就会发生这种情况 // Fails when

我正在使用TypeScript为Firebase中的文档定义数据模型。创建文档时,
createdOn
字段将是服务器时间戳sentinal,否则它是日期。例如

export interface Post<MODE extends 'create' | 'read'> {
  comment: string;
  createdOn: MODE extends 'create' ? FieldValue : Date;
}
然后当我使用它时,就会发生这种情况

// Fails when used within cloud function
// Detected an object of type "FieldValue" that doesn't match the
// expected instance (found in field "createdOn"). Please ensure 
/// that the Firestore types you are using are from the same NPM package.

post.createdOn = SERVER_TIMESTAMP;

// But this works within cloud function

post.createdOn = admin.firestore.FieldValue.serverTimestamp();

从云函数内部和客户端调用FieldValue时,FieldValue的类型是否不同?我可以简单地从云功能和客户端都可用的模块中导入这种类型吗?

Firebase的产品阵容中有相当多的产品,因此它不太直观,这可能会导致混淆。您可以查看所有产品,还可以查看如何正确实现每个库

在您的情况下,似乎缺少firestore,您可以使用以下方式导入firestore:

import * as firebase from 'firebase/app';
import 'firebase/firestore';
然后您可以像这样使用字段值:

const timestamp = firebase.firestore.FieldValue.serverTimestamp();

是关于字段值的更多信息。

我认为这是javascript SDK的一个已知限制问题

如果您从管理员应用程序在Firestore中创建项目,则需要使用与从客户端应用程序创建项目不同的“serverTimestamp”对象

const timestamp = firebase.firestore.FieldValue.serverTimestamp();