Typescript 向firebase集合查询添加键入
我有一个类似于:Typescript 向firebase集合查询添加键入,typescript,firebase,google-cloud-firestore,Typescript,Firebase,Google Cloud Firestore,我有一个类似于: async queryAll(): Promise<Product[]> { const response = await this.firestore.collection('products').get(); return response.docs.map(a => a.data()); } async queryAll():Promise{ const response=wait this.firestore.collection('prod
async queryAll(): Promise<Product[]> {
const response = await this.firestore.collection('products').get();
return response.docs.map(a => a.data());
}
async queryAll():Promise{
const response=wait this.firestore.collection('products').get();
返回response.docs.map(a=>a.data());
}
和获取错误:
类型“DocumentData[]”不能分配给类型“Product[]”。类型
“DocumentData”在类型中缺少以下属性
“产品”:id、名称
如何为该方法添加正确的返回类型
我可以在firebase/index.ts.d
中看到什么,get
函数类型看起来像什么(我使用的是npm firebase包):
获取(选项?:获取选项):承诺代码>
但不确定如何将其应用于我的代码。我找到了解决方案,需要使用 以便在从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[]
}
我发现使用TypeScript的特性来实现这一点非常简单
wait db.collection('products').get()作为firebase.firestore.QuerySnapshot;
对于单个文档:
wait db.collection('products').doc('12345').get()作为firebase.firestore.DocumentSnapshot;
对于快照:
db.collection(“产品”)
.onSnapshot((快照:firebase.firestore.QuerySnapshot)=>{
for(snapshot.docs的const doc){
const product=doc.data();
}
});
当您在文档快照上调用
data()
时,其类型将为Product
b Sekula您能用您的withConverter
发布完整的代码吗?有相同的问题。更新了答案,并添加了示例在onSnapShot()侦听器中如何使用它?@MorenoMdz我添加了一个收集快照的示例。我最终使用了SDK中建议的类型:querySnapshot:firebase.firestore.DocumentData