typescript - 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
解决方案
您的 TypeScript 配置几乎肯定启用了严格的类型检查,当您尝试访问可能为 null 或未定义的属性时,它会给您这个警告。检查您的 tsconfig.json 并"strict": true"
在编译器选项中查找。DataSnapshot.data() API的 TypeScript 绑定表明 data() 的返回值可以是任何值(包括 null 或 undefined),TypeScript 迫使您在编译时正确处理这一事实,以便您的代码不会在运行时崩溃。
您正在查看的示例代码是纯 JavaScript,它没有任何类型检查。假设快照不会为空或未定义。如果您发现这令人困惑或有问题,请使用文档页面顶部的“发送反馈”链接来解释让您感到困惑的地方。
推荐阅读
- c - 在外部声明非常量变量“const”是否合法?
- angular - 除装饰器外的 MSAL 外部配置
- javascript - 如何在函数中使用事件监听器?
- gitlab - Gitlab-CI,按计划运行,但前提是有变化
- java - 可分页属性大小值不生效
- apache-flink - 在路线图上发展 TTL?
- c# - DateTime.TryParseExact 的结果有 DateTimeKind.Unspecified 尽管输入的日期时间字符串包含时区信息
- python-3.x - 是否可以使用 Drive API 获取完整的文档修订历史记录?
- docker - 使用 Jenkins 容器构建 Dockerfile 并部署 Flask 应用
- javascript - 对对象的数字数组进行排序