我在将 typescript 与 firebase 函数一起使用时遇到了问题,尤其是当我从 snapshot.data()
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/