来自函数的数据类型未知 - 函数 v9
Data from function is of type unknown - functions v9
我有一个云功能,可以接收电子邮件和 returns 用户信息,包括 uid。
函数声明如下:
const getUserByEmail = httpsCallable(functions, 'getUserByEmail')
const user = await getUserByEmail({
email: email,
})
但是当我尝试阅读“user.data.id”时,打字稿对我大吼大叫,因为:
"Object is of type 'unknown'.ts(2571) (property)
HttpsCallableResult.data: unknown Data returned from callable function.
我错过了什么?
编辑:我当然试过“user:any”,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
httpsCallable 需要类型信息。
httpsCallable
const getUserByEmail = httpsCallable<{email: string}, {
user: {
data: {
id: string,
}
}
}>(functions, 'getUserByEmail');
const { data } = await getUserByEmail({
email: email,
});
const userId = data.user.data.id;
我有一个云功能,可以接收电子邮件和 returns 用户信息,包括 uid。
函数声明如下:
const getUserByEmail = httpsCallable(functions, 'getUserByEmail')
const user = await getUserByEmail({
email: email,
})
但是当我尝试阅读“user.data.id”时,打字稿对我大吼大叫,因为:
"Object is of type 'unknown'.ts(2571) (property)
HttpsCallableResult.data: unknown Data returned from callable function.
我错过了什么?
编辑:我当然试过“user:any”,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
httpsCallable 需要类型信息。
httpsCallable
const getUserByEmail = httpsCallable<{email: string}, {
user: {
data: {
id: string,
}
}
}>(functions, 'getUserByEmail');
const { data } = await getUserByEmail({
email: email,
});
const userId = data.user.data.id;