Firebase Cloud Functions Object possibly 'undefined'

前端 未结 2 1561
迷失自我
迷失自我 2021-01-21 07:07

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         


        
2条回答
  •  耶瑟儿~
    2021-01-21 07:36

    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 {
        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;
    }
    

提交回复
热议问题