I have the following code in typescript and i get this error on the line: change.after.data();, Object is posibbly \'undefined\':
import * as functi
If you look at the types for the onUpdate handler, the argument for change has 2 optional properties, after and before:
class Change<T> {
before?: T;
after?: T;
constructor(before?: T, after?: T);
}
Because you want to access after, you'll need to wrap it in a conditional, something like this following:
functions.firestore.document("Settings/ShiftsEditMode").onUpdate(change=> {
if (change.after) {
const after = change.after.data();
...
}
}
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);
}
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.
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.
You have two options:
1) Remove that line from your tsconfig.json
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;
}