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


Solution 1:[1]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1