Home > other >  Typescript Generic, how?
Typescript Generic, how?

Time:01-08

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? :)

See test example here: https://www.typescriptlang.org/play?target=8&jsx=0#code/MYewdgzgLgBAhgJwXAnjAvDA2gWAFAwwDe hhAlgCYBcMAjKTAL4A0jJBZVtATI0-gC6 fKEiwA5gFMoAQQA28gCIhgAVwC2UsFAgZ4EFGGAwAPABUAfAApEE2tATkwEgJQZLxRmOgxKqzW1dWnMsQX0wgG5GRGQUADoAMxAEAFE4YAALa2t3dE8OMj8ArR0IeIAHNQhswqKYbhgAcjoeAGYmxkImV2jOHr7GBBk1BDBi9VLdPqZBvCA

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;
};
  •  Tags:  
  • Related