简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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