首页 > 解决方案 > 来自函数的数据类型未知 - 函数 v9

问题描述

我有一个云函数,它接收电子邮件并返回用户信息,包括 uid。

函数声明如下:

const getUserByEmail = httpsCallable(functions, 'getUserByEmail')
const user = await getUserByEmail({
    email: email,
})

但是当我尝试阅读“user.data.id”时,打字稿对我大喊大叫,因为:

“对象的类型为‘未知’.ts(2571)(属性)

HttpsCallableResult.data:可调用函数返回的未知数据。

我错过了什么?

编辑:当然我试过“用户:任何”,TS很高兴,但这不是一个很好的解决方案。

标签: typescriptfirebasegoogle-cloud-functions

解决方案


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


推荐阅读