typescript - 带有 typescript 的云功能,如何定义快照数据的形状?

标签 typescript firebase google-cloud-functions

我在将 typescript 与 firebase 函数一起使用时遇到了问题,尤其是当我从 snapshot.data()

获取值时

enter image description here

snapshot 本身默认使用 firebase 输入,但我如何指定它返回的 data() 的形状?

默认情况下 snapshot.data() 的类型为 DocumentData | undefined,这来自 firebase,我需要以某种方式将其更改为该特定数据的接口(interface)。

最佳答案

你有几个语法选择:

interface Foo {
    a: string
    b: number
}

const foo1 = snapshot.data() as Foo  // cast it
const foo2 = <Foo> snapshot.data()   // also cast it

使用其中任何一个,您可以使用对象解构将其字段放入变量中,如您的答案所示:

const { a, b } = foo1   // automatically assign a and b

如果需要,您可以重新定义局部变量:

const { a: my_a, b: my_b } = foo1   // assigns my_a and my_b instead

这完全是 TypeScript,与数据库 API 毫无关系。

关于typescript - 带有 typescript 的云功能,如何定义快照数据的形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51907198/

相关文章:

javascript - 从 Firebase 数据库填充 Firebase Cloud Functions 中的数组

file-upload - Flutter web - 将图像文件上传到 Firebase 存储

firebase - 如何为 firebase 创建服务帐户以与 firebase 功能一起使用

node.js - 如何动态更改 Mongoose 提供程序中集合或数据库的名称,Nestjs?

angular - 如何解决这个依赖问题

javascript - Firebase 函数读取/访问剩余节点信息

java - Android Firebase UI 无法访问 aad

swift - FCM : Message sent but not received

angular - 在 Angular 方法中返回类值

Angular 8错误: Unexpected value 'HttpClient' imported by the module 'AppModule' .请添加@NgModule注释