You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级Node.js Firebase Admin SDK v10后调用及类型错误求助

Firebase Admin SDK v10 升级错误解决方法

错误1:Cannot find namespace 'messaging'.ts(2503)

v10版本中,messaging命名空间下的类型(比如MessagingDevicesResponse)不再全局暴露,需要从firebase-admin/messaging模块直接导入具体类型。

修改示例:

错误代码:

// 旧写法
const response: messaging.MessagingDevicesResponse = await admin.messaging().sendToDevice(tokens, payload);

修正后代码:

// 先导入对应的类型
import { MessagingDevicesResponse } from "firebase-admin/messaging";
import * as admin from "firebase-admin";

// 使用导入的类型
const response: MessagingDevicesResponse = await admin.messaging().sendToDevice(tokens, payload);

错误2:Type 'DocumentSnapshot' is not generic.ts(2315)

v10版本中,DocumentSnapshot的泛型使用需要明确从firebase-admin/firestore模块导入,不能直接使用全局的DocumentSnapshot。结合云函数functions.Change类型时,要确保类型引用正确。

修改示例:

错误代码:

// 旧写法
export const onUserUpdate = functions.firestore
  .document("users/{userId}")
  .onUpdate((change: functions.Change<DocumentSnapshot<User>>) => {
    const beforeData = change.before.data() as User;
    const afterData = change.after.data() as User;
    // ...业务逻辑
  });

修正后代码:

// 导入所需类型
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import { User } from "./your-user-type-file"; // 假设User类型定义在这个文件

export const onUserUpdate = functions.firestore
  .document("users/{userId}")
  .onUpdate((change: functions.Change<admin.firestore.DocumentSnapshot<User>>) => {
    const beforeData = change.before.data(); // 自动推断为User | undefined
    const afterData = change.after.data();
    // 处理undefined情况
    if (!beforeData || !afterData) return null;
    // ...业务逻辑
  });

简化写法

如果不需要显式声明泛型,也可以通过data()方法的类型断言简化:

const beforeData = change.before.data() as User;

内容的提问来源于stack exchange,提问作者giorgio79

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:40:24