Firebase云函数TypeScript中为Snapshot指定数据类型的问题
为Firebase Cloud Functions的Snapshot指定数据类型的解决方案
你遇到的问题是firebase-functions/v1/firestore导出的QueryDocumentSnapshot并非泛型类型,所以无法直接通过<PaymentDocumentInterface>指定数据类型。以下几种方法可以解决这个问题,且无需声明额外变量做类型转换:
方法1:切换到Firebase Admin SDK的泛型类型
firebase-admin/firestore提供了支持泛型的QueryDocumentSnapshot,只需修改导入源即可:
import { firestore } from "firebase-functions/v1" import { QueryDocumentSnapshot } from "firebase-admin/firestore"; interface PaymentDocumentInterface { amount: number; benefactorDetails: { email: string; marketingConsent: boolean; }; } exports.updateDonationProjectAggregations = firestore.document('protectedEnvironmentData/financialData/payments/{paymentId}').onCreate(async (snapshot: QueryDocumentSnapshot<PaymentDocumentInterface>, context) => { console.log(`Processing payment with value: ${snapshot.data().amount}`); });
方法2:直接在data()调用时添加类型断言
无需修改导入,直接对data()的返回值做类型断言,这是最轻量化的写法:
import { firestore } from "firebase-functions/v1" import { QueryDocumentSnapshot } from "firebase-functions/v1/firestore"; interface PaymentDocumentInterface { amount: number; benefactorDetails: { email: string; marketingConsent: boolean; }; } exports.updateDonationProjectAggregations = firestore.document('protectedEnvironmentData/financialData/payments/{paymentId}').onCreate(async (snapshot, context) => { console.log(`Processing payment with value: ${(snapshot.data() as PaymentDocumentInterface).amount}`); });
方法3:自定义泛型类型扩展原有Snapshot
如果希望保持原有导入源,同时保留泛型声明的写法,可以自己定义一个泛型类型来扩展原有的QueryDocumentSnapshot:
import { firestore } from "firebase-functions/v1" import { QueryDocumentSnapshot as FunctionsSnapshot } from "firebase-functions/v1/firestore"; interface PaymentDocumentInterface { amount: number; benefactorDetails: { email: string; marketingConsent: boolean; }; } // 自定义泛型类型,覆盖data()方法的返回类型 type QueryDocumentSnapshot<T> = FunctionsSnapshot & { data(): T; }; exports.updateDonationProjectAggregations = firestore.document('protectedEnvironmentData/financialData/payments/{paymentId}').onCreate(async (snapshot: QueryDocumentSnapshot<PaymentDocumentInterface>, context) => { console.log(`Processing payment with value: ${snapshot.data().amount}`); });
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

