gpt4 book ai didi

typescript - 将类型添加到 Firebase 集合查询

转载 作者:行者123 更新时间:2023-12-03 17:01:27 26 4
gpt4 key购买 nike

我有一个功能,如:

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

并得到错误:

Type 'DocumentData[]' is not assignable to type 'Product[]'. Type 'DocumentData' is missing the following properties from type 'Product': id, name



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

我可以在 firebase/index.ts.d 中看到什么, get函数类型看起来像(我正在使用 npm firebase 包):
get(options?: GetOptions): Promise<QuerySnapshot<T>>;
但不确定如何将其应用于我的代码。

最佳答案

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

添加了工作示例,result来自 dbQuery函数应该有正确的类型,例如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[]
}

关于typescript - 将类型添加到 Firebase 集合查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60065396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com