0

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)?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Thomas Kuhlmann
  • 943
  • 7
  • 18

1 Answers1

1

You can't avoid calling data() to get the raw data from a document snapshot. It's part of the usual way of dealing with documents from Firestore. It's also not terribly expensive.

Only after you have the raw data in an object, then you can tell typescript what interface the contents should conform to.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441