繁体   English   中英

打字稿:嵌套函数的泛型类型

[英]Typescript: generics type for nested functions

我一直在寻找这个问题的答案,但是我无法正确实现它们。 也许您可以告诉我正确的方法。

我将说明:我想使用打字稿泛型而不在我的方法中使用更多的“任何”。

我正在编写代码以及我想做什么。

在组件中:

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

当我调用getCollection()时,我将调用以下嵌套方法:

  • getCollectionSnapshot()
  • getCollectionRef()

我希望将传递给getCollection()的类型(IUser)转发给已初始化的方法,直到到达getCollectionRef()以获得该类型的返回集合:collection

文件服务: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));
    }
}

谢谢 ! 我希望填补我在仿制药方面的空白

我不确定我是否理解你的问题。 你想传递的方法getCollection到名为内getCollection方法给出的类型参数。 如果是这样,那么它适合您:

getCollection <T> (path: string, sortBy ?: string): Observable <T []>
{ 

    return this.getCollectionSnapshot<T> (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<T> (path: string, sortBy ?: string): Observable <any []>
{
    return this.getCollectionRef<T> (path, sortBy) .snapshotChanges ();
}

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

注意更改:

getCollectionSnapshot <T> (...

getCollectionRef <T> (...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM