简体   繁体   English

Object 可能在 TypeScript 中未定义

[英]Object is possibly undefined in TypeScript

I did use sfDoc !== undefined , but still I'm getting the error of object is possibly undefined.我确实使用sfDoc !== undefined ,但我仍然收到 object 的错误可能是未定义的。 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.检查 sfDoc 并返回transaction.update ,然后等待解析 promise。 According to document, you don not has to check for sfDoc .根据文档,您不必检查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;
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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