typescript - 来自函数的数据类型未知 - 函数 v9
问题描述
我有一个云函数,它接收电子邮件并返回用户信息,包括 uid。
函数声明如下:
const getUserByEmail = httpsCallable(functions, 'getUserByEmail')
const user = await getUserByEmail({
email: email,
})
但是当我尝试阅读“user.data.id”时,打字稿对我大喊大叫,因为:
“对象的类型为‘未知’.ts(2571)(属性)
HttpsCallableResult.data:可调用函数返回的未知数据。
我错过了什么?
编辑:当然我试过“用户:任何”,TS很高兴,但这不是一个很好的解决方案。
解决方案
TS 不知道用户是什么。您必须实现用户类型保护。
查看文档中的示例 TS 如何理解每个if
分支中的类型:
function f(x: unknown) {
if (typeof x === "string" || typeof x === "number") {
x; // string | number
}
if (x instanceof Error) {
x; // Error
}
if (isFunction(x)) {
x; // Function
}
}
对于您的问题,例如:
export const isUser(x: any): x is User {
//here you have to check out props so you are sure x is user
}
有关更多信息,请查看https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
推荐阅读
- html - 来自磁盘缓存的 html5 applicationCache
- javascript - 我怎样才能获得特定收音机的价值
- indexing - WordDelimiterGraphFilterFactory 的 Solr 短语查询问题
- rxjs - 在 Redux Observable 中,如何在 img 加载后获取图像大小
- dart - 在 Dart 中检测动态类型
- arrays - 将一维数组重塑为网格格式
- typo3 - TYPO3 9.2.1 在 Composer 模式下创建 ViewHelper
- angular - 在 typescript [ionic angular] 中执行 resolveLocalFilesystemUrl 后无法获取文件数据
- android - 如何在gradle中声明一个变量?
- mysql - 1615 准备好的语句需要在codeigniter中重新准备