Firebase获取服务器时间戳时出现命名空间错误求助
修复Firestore服务器时间戳函数的返回类型错误
你的代码有三个核心问题,直接导致返回类型不匹配:
- 返回类型标注错误:当前代码未引入
firebase命名空间,不能用firebase.firestore.Timestamp;且FieldValue.serverTimestamp()返回的不是Timestamp,是占位符类型FieldValue,该值只有写入Firestore后才会被解析为服务器时间戳。 - FieldValue引用错误:你用了未定义的
FirebaseFirestore或firebase命名空间,应该用已引入的admin.firestore调用相关方法。 - 冗余变量:代码里定义的
const fs = admin.firestore();未被使用,可直接删除。
修复后的代码:
import * as functions from "firebase-functions"; import * as admin from "firebase-admin"; admin.initializeApp(); /** * 返回Firestore的服务器时间戳占位符 * 写入Firestore后会自动解析为服务器端的Timestamp * * @returns {admin.firestore.FieldValue} 服务器时间戳占位符 */ export function getServerTimestamp(): admin.firestore.FieldValue { return admin.firestore.FieldValue.serverTimestamp(); }
额外说明:
- 若你需要获取即时的Timestamp对象(而非写入用的占位符),可直接使用
admin.firestore.Timestamp.now(),此时返回类型为admin.firestore.Timestamp。 - 你避免多余命名空间引入的思路是正确的,直接用已引入的
admin下的Firestore相关类型和方法,不会增加冷启动负担。
内容的提问来源于stack exchange,提问作者whatwhatwhat
相关产品推荐
相关产品推荐

