首页 > 解决方案 > 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 对象。

这是文档中的代码:

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

标签: typescriptgoogle-cloud-functions

解决方案


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

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


推荐阅读