Firebase Cloud Functions对象可能“未定义" [英] Firebase Cloud Functions Object possibly 'undefined'
问题描述
我在打字稿中有以下代码,并且在行上遇到此错误:change.after.data();
,对象可能是未定义":
I have the following code in typescript and i get this error on the line: change.after.data();
, Object is posibbly 'undefined':
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
admin.initializeApp()
export const onEditModeUpdate =
functions.firestore.document("Settings/ShiftsEditMode").onUpdate(change=> {
const after = change.after.data();
const payload = {
data: {
temp: String(after.temp),
conditions: after.conditions
}
}
return admin.messaging().sendToTopic("Settings/ShiftsEditMode", payload)
})
我想要做的是,只要firestore中的某些内容发生变化,就向我的应用发送通知,我遵循了官方文档,但出现错误,我认为这与node.js版本有关.有什么帮助吗?
what I want to do is to send to my app a notification whenever something in firestore changes, I followed the official documentation but I get the error, I think this has to do with node.js version. Any help, please?
推荐答案
您的change
参数的类型为Change.如果在VSCode中单击它,您将在这里看到它的定义:
Your change
parameter is of type Change. If you click through to it in VSCode, you'll see it's definition here:
export declare class Change<T> {
before?: T;
after?: T;
constructor(before?: T, after?: T);
}
请注意,它的before
和after
属性都是可选的,并在类型中标有?
.这意味着可能未定义值.
Notice that its before
and after
properties are both optional, marked with a ?
in the type. This means that it's possible that the values are undefined.
tsconfig.json
中的TypeScript配置很可能包含"strict": true
的行,该行告诉TypeScript每当您尝试访问未明确检查而未定义的属性时都不会警告您.那就是你在这里看到的错误.
It's likely that your TypeScript config in tsconfig.json
contains a line for "strict": true
, which tells TypeScript not warn you whenever you try to access a property that could be undefined without explicitly checking it first. That's the error you're seeing here.
您有两个选择:
1)从tsconfig.json中删除该行
1) Remove that line from your tsconfig.json
2)或检查是否首先定义了
2) Or check to see if it's defined first
if (change.after) {
const after = change.after.data();
const payload = {
data: {
temp: String(after.temp),
conditions: after.conditions
}
}
return admin.messaging().sendToTopic("Settings/ShiftsEditMode", payload)
}
else {
return null;
}
这篇关于Firebase Cloud Functions对象可能“未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!