简体   繁体   English

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

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

For example i have this code.例如我有这段代码。 API can return data of 4 different Interfaces. API可以返回4个不同接口的数据。 How can i dynamically pass the interface to function call?如何动态地将接口传递给 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();

I was trying to add a generic to the service method, but i can't figure out how to pass interface to function call from component, to get that interface from the response.我试图向服务方法添加一个泛型,但我无法弄清楚如何将接口传递给组件的 function 调用,以从响应中获取该接口。 So if my linkName === 'one' i want to pass an interface named One and so on.因此,如果我的linkName === 'one'我想传递一个名为One的接口,依此类推。

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

I don't believe you can do that, but you can give a type to T like so:我不相信你能做到这一点,但你可以像这样给 T 一个类型:

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

This way you make sure that no matter what object you throw into the generic it has to be something that implements said interface.通过这种方式,您可以确保无论将什么 object 放入泛型中,它都必须是实现所述接口的东西。 Use it like so:像这样使用它:

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

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

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