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

查看:884
本文介绍了云函数-TypeScript-“对象可能是'undefined'.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()的TypeScript绑定. API表示data()的返回值可以是任何值(包括null或未定义),并且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.

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

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