I have a function to get all documents from a DB in Firebase The function itself can be used to retrieve any kind of document, which is why I need to specify whatever it returns with a generic..
Im doing this at the moment:
export const getAllDocuments = async <DocType>(collectionName: string) => {
const documents: DocType[] = [];
const querySnapshot = await getDocs(collection(db, collectionName));
querySnapshot.forEach((doc) => {
documents.push({
id: doc.id,
...doc.data(),
});
});
return documents;
};
But im getting this error: "TS2345: Argument of type '{ id: string; }' is not assignable to parameter of type 'DocType'. 'DocType' could be instantiated with an arbitrary type which could be unrelated to '{ id: string; }'" ??
Im calling the function like so:
const documents = await getAllDocuments<ExerciseDocument>('exercises');
What am I doing wrong here? :)
CodePudding user response:
you can try
const getAllDocuments = async <T extends { id: string }>(arg: string) => {
const documents: T[] = [];
array.forEach(() => {
documents.push({
id: '123'
} as T);
});
return documents;
};