首页 > 解决方案 > 向 Firebase 集合查询添加类型

问题描述

我有一个类似的功能:

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<QuerySnapshot<T>>;

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

标签: typescriptfirebasegoogle-cloud-firestore

解决方案


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

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

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[]
}

推荐阅读