0

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

在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 

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

4

1 回答 1

1

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

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

于 2020-01-24T16:26:22.290 回答