Typescript: generics type for nested functions

I have looked for answers to this problem but I can not implement them correctly. Maybe you can tell me the right way.

I’ll explain: I want to use typescript generics not to use any more ‘Any’ in my methods.

I am writing the code and what I would like to do.

IN THE COMPONENT:

this.DatabaseService.getCollection <IUser> ('users', 'lastname'). subscribe (loadData =>
{
    this.listUser = loadData;
});

when I call getCollection () I will call the following nested methods:

  • getCollectionSnapshot()
  • getCollectionRef()

I want the type (IUser) passed to getCollection () to be forwarded to the nitidicated methods until you reach getCollectionRef () obtaining a return collection of this type: collection

FILE SERVICE: database.service.ts

getCollection <T> (path: string, sortBy ?: string): Observable <T []>
{
    // >>>how do I pass the type (T) to getCollectionSnapshot() ? 

    return this.getCollectionSnapshot (path, sortBy) .pipe (
    map (changes =>
    {
        return changes.map (change =>
        {
            const data = change.payload.doc.data ();
            const id = change.payload.doc.id;
            return {id, ... data};
        });
     }
     ));
}


getCollectionSnapshot (path: string, sortBy ?: string): Observable <any []>
{
    return this.getCollectionRef (path, sortBy) .snapshotChanges ();
}



getCollectionRef (path: string, sortBy ?: string): AngularFirestoreCollection
{
    if (sortBy === undefined)
    {
      return this.afs.collection (path);
    }
    else
    {
      return this.afs.collection (path, ref => ref.orderBy (sortBy));
    }
}

Thank you ! I hope to fill my gap in generics

Source: Angular

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.