I am creating a trigger function using Firebase Cloud Functions in TypeScript, and would like to assign the type of the data held in the snapshot directly in the onCreate
function as such:
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: QueryDocumentSnapshot<PaymentDocumentInterface>, context) => {
console.log(`Processing payment with value: ${snapshot.data().amount}`);
});
When I attempt to do so, TS complains, saying:
Type ‘QueryDocumentSnapshot’ is not generic
Is there another way to assign the correct return type to the snapshot’s data()
method, before the main code block?
I am not interested in declaring a new data variable and casting it with the appropriate type.
2
Answers
Try with that import instead which is generic
As stated by your error, the
functions.firestore.QueryDocumentSnapshot
of the event handler is defined asQueryDocumentSnapshot<DocumentData>
. In regular Firestore SDK use, you changeDocumentData
to something else using the query’swithConverter(converter)
method before executing it.If you want to change
DocumentData
to a different type you have two options:Option 1: Feed it through a
FirestoreDataConverter
.Option 2: Manually cast it (not recommended, but fine for basic interfaces).
OR