【问题标题】:Add typings to firebase collection query向 Firebase 集合查询添加类型
【发布时间】:2020-02-04 20:53:04
【问题描述】:

我有一个类似的功能:

async queryAll(): Promise<Product[]> {
  const response = await this.firestore.collection('products').get();
  return response.docs.map(a => a.data());
}

得到错误:

类型“DocumentData[]”不可分配给类型“Product[]”。类型 “DocumentData”缺少类型中的以下属性 “产品”:ID、名称

如何为此方法添加正确的返回类型?

我在firebase/index.ts.dget 函数类型中可以看到什么(我使用的是 npm firebase 包):

get(options?: GetOptions): Promise&lt;QuerySnapshot&lt;T&gt;&gt;;

但不确定如何将其应用于我的代码。

【问题讨论】:

    标签: typescript firebase google-cloud-firestore


    【解决方案1】:

    我找到了解决方案,需要使用 withConverter 以便在从 Firestore 集合中检索数据时添加类型

    添加了工作示例,来自dbQuery 函数的result 应该具有正确的类型,例如Product[]

    import firebase from 'firebase';
    import { firebaseConfig } from '../firebaseConfig';
    
    export interface Product {
      name: string;
    }
    
    export const productConverter = {
      toFirestore(product: Product): firebase.firestore.DocumentData {
        return { name: product.name };
      },
    
      fromFirestore(
        snapshot: firebase.firestore.QueryDocumentSnapshot,
        options: firebase.firestore.SnapshotOptions
      ): Product {
        const data = snapshot.data(options)!;
        return { name: data.name }
      }
    };
    
    async function dbQuery() {
      firebase.initializeApp(firebaseConfig);
      const db = firebase.firestore();
      const response = await db.collection("products").withConverter(productConverter).get();
      const result = response.docs.map(doc => {
        const data = doc.data();
        return data;
      });
    
      return result; // result type is Product[]
    }
    

    【讨论】:

    • bsekula 你能用你的withConverter 发布完整的代码吗?有同样的问题。
    • 用示例更新答案
    【解决方案2】:

    我发现使用 TypeScript 的 Type assertions 功能非常简单。

    await db.collection('products').get() as firebase.firestore.QuerySnapshot<Product>;
    

    对于单个文档:

    await db.collection('products').doc('12345').get() as firebase.firestore.DocumentSnapshot<Product>;
    

    对于快照:

    db.collection('products')
      .onSnapshot((snapshot: firebase.firestore.QuerySnapshot<Product>) => {
        for (const doc of snapshot.docs) {
          const product = doc.data();
        }
      });
    

    当您在文档快照上调用data() 时,其类型将为Product

    【讨论】:

    • 如何在 onSnapShot() 监听器中使用它?
    • @MorenoMdz 我添加了一个收集快照的示例
    • 嘿,我最终使用了 SDK 中建议的类型:querySnapshot: firebase.firestore.DocumentData
    猜你喜欢
    • 2021-06-29
    • 1970-01-01
    • 2016-10-20
    • 2023-03-12
    • 1970-01-01
    • 2019-03-27
    • 2012-10-25
    • 2012-05-19
    • 1970-01-01
    相关资源
    最近更新 更多