繁体   English   中英

如何将接口作为通用类型动态传递给 function 调用

[英]how to dynamically pass Interface as generic type to function call

例如我有这段代码。 API可以返回4个不同接口的数据。 如何动态地将接口传递给 function 调用?

// Service
getCandidateConnectedProfiles<T>(source: string, candidateId: string): Observable<T> {
      return this.http
        .get<ServerResponse<T>>(`${apis.getCandidateConnectedProfiles}/${source}/${candidateId}`)
        .pipe(
          map(response => response.result)
        );
    }
// Component
this.candidateProfileService.getCandidateConnectedProfiles(linkName.toLowerCase(), linkId)
.subscribe();

我试图向服务方法添加一个泛型,但我无法弄清楚如何将接口传递给组件的 function 调用,以从响应中获取该接口。 因此,如果我的linkName === 'one'我想传递一个名为One的接口,依此类推。

this.candidateProfileService.getCandidateConnectedProfiles<Here i want my interface depending on linkName>(linkName.toLowerCase(), linkId)
.subscribe();

我不相信你能做到这一点,但你可以像这样给 T 一个类型:

getCandidateConnectedProfiles<T extends InterfaceA>(source: string, candidateId: string)

通过这种方式,您可以确保无论将什么 object 放入泛型中,它都必须是实现所述接口的东西。 像这样使用它:

this.candidateProfileService.getCandidateConnectedProfiles<someSubtypeOfInterfaceA>(linkName.toLowerCase(), linkId)

暂无
暂无

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

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