![](/img/trans.png)
[英]TypeScript and Firebase cloud functions: object is of type 'unknown'
[英]Firebase cloud functions - typescript - undefine type
我這里有一個有趣的問題......
我使用了firestore-events的官方文檔
從那里我得到這個代碼,以測試和玩。
exports.countNameChanges = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
// Retrieve the current and previous value
const data = change.after.data();
const previousData = change.before.data();
// We'll only update if the name has changed.
// This is crucial to prevent infinite loops.
if (data.name == previousData.name) return null;
// Retrieve the current count of name changes
let count = data.name_change_count;
if (!count) {
count = 0;
}
// Then return a promise of a set operation to update the count
return change.after.ref.set({
name_change_count: count + 1
}, { merge: true });
});
那些我把它們放進去的那些(所以也許我想念一個)
import * as functions from 'firebase-functions';
import * as Storage from '@google-cloud/storage';
const gcs = new Storage.Storage();
我認為它看起來很好,但我收到此錯誤消息:
src/index.ts:33:13 - error TS2532: Object is possibly 'undefined'.
33 if (data.name == previousData.name) return null;
~~~~
src/index.ts:33:26 - error TS2532: Object is possibly 'undefined'.
33 if (data.name == previousData.name) return null;
~~~~~~~~~~~~
src/index.ts:36:21 - error TS2532: Object is possibly 'undefined'.
36 let count = data.name_change_count;
~~~~
這是怎么回事? 我在這里缺少什么? 有誰知道我做錯了什么,可以幫助我嗎? 我認為一切都應該在文檔中很好並且可行。
事實上,它是工作代碼,唯一抱怨的是你的短信。
實際上,問題是onUpdate
在創建,更新或刪除文檔時觸發,因此如果文檔被刪除則可能無法定義change.after.data()
,這就是change.after.data()
抱怨的原因。
如果您的意圖開始,我建議您在任何抱怨的行上使用// @ts-ignore
,然后當您感覺更加舒適時,您可以調查更多,這種情況是進行一些驗證以確保您正在執行該行,如:
if (previousData && data.name == previousData.name) return null;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.