在TypeScript中可能未定义对象

时间:2020-04-27 16:41:18

标签: javascript typescript firebase google-cloud-firestore google-cloud-functions

我确实使用过sfDoc !== undefined,但仍然收到对象错误可能未定义。我在这里做错什么了吗?

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

1 个答案:

答案 0 :(得分:1)

尝试以下示例。检查sfDoc并返回# mapping for domain-label conversion domains_mapping = {"com": "Commercial", "org": "Organization", "net": "network", "info": "Information"} urls = ["en.wiki.org", "codesignal.com", "happy.net", "code.info"] # using list comprehension, we extract the domain for each url and get the corresponding label using our mapping output = [domains_mapping.get(u.split(".")[-1]) for u in urls] print(output) # ['Organization', 'Commercial', 'network', 'Information'] ,以便等待解决承诺。根据文档,您不必检查transaction.update。它将始终被定义。

sfDoc