将类型添加到 Firebase 集合查询

bse*_*ula 6 firebase typescript google-cloud-firestore

我有一个功能,如:

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

并得到错误:

类型“DocumentData[]”不可分配给类型“Product[]”。“DocumentData”类型缺少“Product”类型中的以下属性:id、name

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

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

get(options?: GetOptions): Promise<QuerySnapshot<T>>;

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

bse*_*ula 9

我找到了解决方案,需要使用 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[]
}
Run Code Online (Sandbox Code Playgroud)