简体   繁体   中英

Object is possibly undefined in TypeScript

I did use sfDoc !== undefined , but still I'm getting the error of object is possibly undefined. Am I doing anything wrong here?

return database.runTransaction(function (transaction) {
    return transaction.get(sfDocRef).then(sfDoc => {
        if (!sfDoc.exists) {
            throw "Document does not exist!";
        }
        if (sfDoc !== undefined) {
            var usedCount = sfDoc.data().usedCount + 1;
            transaction.update(sfDocRef, { usedCount: usedCount });    
        }
        return transaction;
    });
}).then(function () {
    console.log("Tag field changed!");
    return true;
}).catch(function (error) {
    console.log("Error in changing Tag field: ", error);
    return false;
});

Try this example. Check for the sfDoc and return transaction.update , So that then wait to resolve the promise. According to document, you don not has to check for sfDoc . It will be always defined.

return database
  .runTransaction(function (transaction) {
    return transaction.get(sfDocRef).then((sfDoc) => {
      if (sfDoc && sfDoc.exists) {
        var usedCount = sfDoc.data().usedCount + 1;
        return transaction.update(sfDocRef, { usedCount: usedCount });
      } else {
        throw "Document does not exist!";
      }
    });
  })
  .then(function () {
    console.log("Tag field changed!");
    return true;
  })
  .catch(function (error) {
    console.log("Error in changing Tag field: ", error);
    return false;
  });

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