Cloud Functions-TypeScript-“对象可能是'未定义'.ts(2532)" [英] Cloud Functions-TypeScript- "Object is possibly 'undefined'.ts(2532)"

查看:248
本文介绍了Cloud Functions-TypeScript-“对象可能是'未定义'.ts(2532)"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

export const newPost = functions.firestore
.document('post/{postId}/')
.onCreate((snap, context) => {

    const postData = snap.data()
    const authorId = postData.uid    
});

我收到 postData 可能未定义的错误,解决此问题的方法是检查 postData != null 是否在 {} 内使用 postData 对象.

I get the error that postData is possibly undefined, the way around this is to check if postData != null and then inside {} use postData object.

这是文档中的代码:

exports.createUser = functions.firestore
.document('users/{userId}')
.onCreate((snap, context) => {
  // Get an object representing the document
  // e.g. {'name': 'Marie', 'age': 66}
  const newValue = snap.data();

  // access a particular field as you would any JS property
  const name = newValue.name;

  // perform desired operations ...
});

这里没有提到可能存在未定义的对象newValue,同样通过阅读许多带有firestore的云函数示例,我没有看到人们会在使用它之前检查是否.data()!= null

It is not mentioned here that there could be undefined object newValue, also by reading many examples of cloud functions with firestore I haven't seen that people would check if .data() != null before using it

推荐答案

您的 TypeScript 配置几乎肯定启用了严格的类型检查,当您尝试访问可能为 null 或未定义的属性时,它会给您这个警告.检查您的 tsconfig.json 并在编译器选项中查找 "strict": true".DataSnapshot.data() API 说 data() 的返回值可以是任何东西(包括 null 或 undefined),TypeScript 强迫你在编译时正确处理这个事实,这样你的代码就不会在运行时崩溃.

Your TypeScript configuration almost certainly has strict type checking enabled, which will give you this warning when you try to access properties of something that could be null or undefined. Check your tsconfig.json and look for "strict": true" in the compiler options. The TypeScript bindings for the DataSnapshot.data() API says that the return value of data() could anything (including null or undefined), and TypeScript is forcing you to deal with this fact correctly at compile time so that your code doesn't crash at runtime.

您正在查看的示例代码是纯 JavaScript,它没有任何类型检查.假设快照不会为空或未定义.如果您发现这令人困惑或有问题,请使用文档页面顶部的发送反馈"链接来解释让您感到困惑的地方.

The sample code you're looking at is plain JavaScript, which does not have any type checking. It is assuming that the snapshot will not be null or undefined. If you found this to be confusing or problematic, please use the "send feedback" link at the top of the page of documentation to explain what was confusing to you.

这篇关于Cloud Functions-TypeScript-“对象可能是'未定义'.ts(2532)"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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