typescript - 向 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.d
,get
函数类型看起来像(我正在使用 npm firebase 包):
get(options?: GetOptions): Promise<QuerySnapshot<T>>;
但不确定如何将其应用于我的代码。
解决方案
我找到了解决方案,需要使用 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[]
}
推荐阅读
- forms - 如何在选择文件窗口上按取消并在 powershell 中重新启动程序
- tensorflow - 为 TensorFlow.js 保存 TensorFlow 模型
- python - 使用 Python 脚本在 ParaView 中绘制一条线上变量的积分与时间的关系
- apache-spark - 使用 k-means 聚类时如何设置 spark 配置以减少洗牌?
- php - 使用 apache 服务器在 PHP 应用程序中获取 client_ip
- javascript - json数据检查相同的id是否重复
- php - Laravel update join table
- angularjs - Call web api post method in a loop
- ios - Add Hyperlink to Storyboard using Swift
- android - Clipboard clip change listener not working when app closed in Android Oreo