如何动态传递接口作为通用类型以函数调用

发布于 2025-01-26 19:27:04 字数 826 浏览 3 评论 0原文

例如,我有此代码。 API可以返回4个不同接口的数据。如何动态传递接口函数调用?

// 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();

我试图在服务方法中添加通用,但是我不知道如何将接口从组件函数调用,从而从响应中获取该接口。因此,如果我的 linkName ==='一个''我想传递一个名为一个的接口,依此类推。

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

For example i have this code. API can return data of 4 different Interfaces. How can i dynamically pass the interface to function call ?

// 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. So if my linkName === 'one' i want to pass an interface named One and so on.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随遇而安 2025-02-02 19:27:04

我不相信您可以做到这一点,但是您可以像这样这样做类型:

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

这样,您要确保无论您将哪种对象投入通用的对象,都必须是实现界面的某些东西。像这样使用:

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

I don't believe you can do that, but you can give a type to T like so:

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. Use it like so:

this.candidateProfileService.getCandidateConnectedProfiles<someSubtypeOfInterfaceA>(linkName.toLowerCase(), linkId)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文