簡體   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