简体   繁体   中英

Firebase cloud functions - typescript - undefine type

I have an interesting problem here...

I used the official documentation for firestore-events

and from there I get this code in order to test and playing around.

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

with those import's which I've put them (so maybe I miss one)

import * as functions from 'firebase-functions';

import * as Storage from '@google-cloud/storage';
const gcs = new Storage.Storage();

I think everything it looks fine but I get this error message:

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;
                       ~~~~

What's going on? What I'm missing here? Is anyone knowing what I'm doing wrong and can help me? I was thinking that everything should be fine and workable in the documentation.

It is, in fact, working code, the only thing complaining is your linter.

Actually, the problem is that onUpdate triggers when the doc is created, updated or deleted, so it is possible that change.after.data() is undefined if the document is deleted, that's why the linter is complaining.

I would recommend you to use // @ts-ignore on top on any line that is complaining if your intention is getting started, then later when you feel more confortable, you can investigate more which is this case is to put some validation to ensure that you are executing that line like:

if (previousData && data.name == previousData.name) return null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM