我已经尝试了一段时间来做一些应该非常简单的事情,但我一直遇到问题。
在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
)?