I have been trying for a while now to do something that should be very simple but I keep running into problems.
What is the correct way to destructure the snapshot parameter in a firestore cloud function trigger and assign types?
Here's how the code looks like that's working:
export default (region: any) =>
functions
.region(region)
.firestore.document(
"organisations/{organisationID}/workspaces/{workspaceID}"
)
.onCreate(
async (snap: FirebaseFirestore.DocumentSnapshot, context: functions.EventContext) => {
const data = snap.data() as CustomType
...do something else
}
}
what I am trying to instead is to avoid the initial const data = snap.data() as CustomType
inside the function:
export default (region: any) =>
functions
.region(region)
.firestore.document(
"organisations/{organisationID}/workspaces/{workspaceID}"
)
.onCreate(
async ({data, ref}:{data:()=> CustomType, ref:FirebaseFirestore.DocumentReference }, context: functions.EventContext) => {
...do something else
}
}
But when I try this, I keep getting errors:
Argument of type '({ data, ref }: { data: () => CustomType; ref: FirebaseFirestore.DocumentReference; }, context: functions.EventContext) => Promise<void>' is not assignable to parameter of type '(snapshot: DocumentSnapshot, context: EventContext) => any'.
Types of parameters '__0' and 'snapshot' are incompatible.
Type 'DocumentSnapshot' is not assignable to type '{ data: () => CustomType; ref: DocumentReference; }'.
The types returned by 'data()' are incompatible between these types.
Type 'DocumentData | undefined' is not assignable to type 'CustomType'.
Type 'undefined' is not assignable to type 'CustomType'.
Type 'undefined' is not assignable to type
Am I doing something wrong? And if I am not, is there a way to force the type on the return value (similar to when I declare const data = snap.data() as CustomType
)?