'DocumentData | 类型的参数 undefined' 不可分配给类型为 'DocumentData' 的参数

ins*_*ing 0 typescript google-cloud-functions google-cloud-firestore

首先,我想说我的很多代码可能很糟糕,所以我很抱歉。我的 .ts 和 .js 经验并不是让我感到非常舒服的时候(因此我无法解决这个问题)。所以我试图将文档内容从一个文档获取到另一个文档。目前是通过快照来完成的,但我确信有更快更好的方法。我的代码如下。

当我尝试将第二个集合 (redacted2) 的文档设置为快照数据时,会发生错误。正如您从控制台日志中可以看出的,我知道 snapshot.data() 具有我需要的有价值的信息,我需要完全按照我希望的方式对其进行格式化。我假设这类似于在 swift 中有一个保护语句,我可以在其中检查 null 的值并将其分配给给定的类型(但我在这里可能是错的)。

                db.collection("Redacted").doc(context.params.sensors).get()
                .then(function(querySnapshot){
                    console.log("Query Snapshot is is isssss: ", querySnapshot)
                    console.log("Query Snapshot querySnapshot.data: ", querySnapshot.data)
                    console.log("Query Snapshot querySnapshot.data(): ", querySnapshot.data())
                    console.log("Query Snapshot querySnapshot.ref: ", querySnapshot.ref)
                    console.log("Query Snapshot querySnapshot.get: ", querySnapshot.get)

                    return querySnapshot
                }).then(function(querySnapshotData) {
                    console.log("ayoooooo blooooddd", querySnapshotData)
                    db.collection("Redacted2").doc(context.params.sensors).set(querySnapshotData.data())
                        .then((alertResponse1: any) => {
                            console.log("Successfully updated firestore: ", alertResponse1)
                        })
                        .catch ((alertError1: any) => {
                            console.log("Successfully updated firestore but with error: ", alertError1)
                        })
                })
                .catch(function(error) {
                    console.log("query snapshot error: ", error)
                });
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 5

正如您从DocumentSnapshot.data()API 文档中所见,data()声明为返回DocumentDataundefinedundefined如果文档不存在,则可能是这样。TypeScript 不会让你在可能是的东西上调用方法undefined,因为这会在运行时产生错误。您必须向 TypeScript 保证其结果实际上是 aDocumentData而 never undefined

const data = snapshot.data()
if (data) {
    // data will never be undefined here, because we just checked that.
    const foo = data.foo
}
Run Code Online (Sandbox Code Playgroud)