Issue
I have a function like:
async queryAll(): Promise<Product[]> {
const response = await this.firestore.collection('products').get();
return response.docs.map(a => a.data());
}
And getting error:
Type 'DocumentData[]' is not assignable to type 'Product[]'. Type 'DocumentData' is missing the following properties from type 'Product': id, name
How can I add proper return typings for this method?
What can I see in firebase/index.ts.d
, get
function types looks like (I am using npm firebase package):
get(options?: GetOptions): Promise<QuerySnapshot<T>>;
But not sure how to apply this to my code.
Solution
I have found solution, need to use withConverter in order to add typings when retrieving data from firestore collections
Added working example, result
from dbQuery
function should have proper type i.g. 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[]
}
Answered By - bsekula
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.