如何使用 Google Cloud 函数将 DocumentSnapshot 中的数据转换为自定义类型,以便利用自动完成功能?

tla*_*lco 3 typescript google-cloud-functions typescript-typings google-cloud-firestore

我真的很喜欢这样一个事实,即在用 typescript 开发云函数时,firebase 有一些非常好的类型。我希望能够对数据库中的实体(如用户等)使用自动完成功能。如何正确创建类?

我认为它应该是这样的

type User = {
  activeUntil: admin.firestore.Timestamp
  createdAt: admin.firestore.Timestamp
  sex: 'men' | 'woman'
  name: string
}

export default async function onCreate (snap : FirebaseFirestore.DocumentSnapshot) {
    const user:User= snap.data()
    console.log('user:- ', user)
    return
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:我收到以下错误:类型 'DocumentData' 缺少来自类型 'User' 的以下属性:activeUntil、createdAt、sex、name。

Dou*_*son 10

如果您的文档字段与类型或接口描述完全匹配,您可以简单地将返回的 DocumentData 对象snap.data()转换为该类型。

const user = snap.data() as User
Run Code Online (Sandbox Code Playgroud)

请记住,运行时的任何不一致都可能导致问题,例如,缺少文档字段或联合类型中的意外字符串。简单地进行转换可能很方便,但您需要非常确信一切都将符合类型或界面的形状。

  • 我无法谈论最佳实践。如果您想使用它,该选项就在那里。如果您想万无一失,则应在投射之前检查来自数据库的所有内容,因为 Firestore 无法对每个字段中的数据类型做出任何保证。 (2认同)