如何解构 Cloud Function 参数?

How to destructure Cloud Function parameters?

我已经尝试了一段时间来做一些应该非常简单的事情,但我一直 运行 遇到问题。

在 firestore 云函数触发器中解构快照参数并分配类型的正确方法是什么?

下面是代码的工作原理:

    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
          }
        }

我想做的是避免函数中的初始 const data = snap.data() as CustomType

  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
              }
            }

但是当我尝试这样做时,我不断收到错误消息:

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 

我做错了什么吗?如果我不是,有没有办法强制 return 值的类型(类似于我声明 const data = snap.data() as CustomType 时的类型)?

您无法避免调用 data() 从文档快照中获取原始数据。这是处理来自 Firestore 的文档的常用方式的一部分。它也不是很贵。

只有在对象中拥有原始数据后,您才能告诉打字稿内容应该符合什么接口。