如何解决错误"TS2532:对象可能为“未定义"? [英] How can I solve the error 'TS2532: Object is possibly 'undefined'?

查看:2088
本文介绍了如何解决错误"TS2532:对象可能为“未定义"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重建一个使用Firebase Cloud Functions和Firestore的Web应用程序示例.部署功能时,出现以下错误:

I'm trying to rebuild a web app example that uses Firebase Cloud Functions and Firestore. When deploying a function I get the following error:

src/index.ts:45:18 - error TS2532: Object is possibly 'undefined'.
45     const data = change.after.data();

这是功能:

export const archiveChat = functions.firestore
  .document("chats/{chatId}")
  .onUpdate(change => {
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
  });

我只是在尝试部署该功能以对其进行测试.并且已经在网上搜索了类似的问题,但是找不到与我的问题匹配的其他帖子.

I'm just trying to deploy the function to test it. And already searched the web for similar problems, but couldn't find any other posts that match my problem.

推荐答案

自2019年10月起,TypeScript 3.7(Beta)上现在提供了可选链接(?运算符).您可以通过运行以下命令来安装该版本:

As of October 2019, optional chaining (the ? operator) is now available on TypeScript 3.7 (Beta). You may install that version by running the following command:

npm install typescript@beta

这样,您可以将表达式简化为以下内容:

As such, you can simplify your expression to the following:

const data = change?.after?.data();

您可以从发行说明,其中涵盖了该版本上发布的其他有趣功能.

You may read more about it from the release notes, which cover other interesting features released on that version.

更新(截至2019年11月)

Update (as of November 2019)

TypeScript的可选链接现已正式可用.安装最新版本的打字稿应该可以访问一些很酷的新功能.

TypeScript's optional chaining is now officially available. Installing the latest version of typescript should allow you to access the cool new features.

npm install typescript

话虽这么说,可选链接可以与无效在处理nullundefined

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

这篇关于如何解决错误"TS2532:对象可能为“未定义"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆