Search code examples
angulartypescriptangular-httpclient

Why is Angular not choosing correct overload for HttpClient.get(...)?


I'm trying to abstract out some HttpClient calls (.get(...) and .post(...)) into a BaseService class since I'm having to duplicate code such as headers and credentials if my services don't inherit from a base class.

In doing this, for some reason my code isn't choosing the generic overload on the get.

The following method call is successfully choosing the correct HttpClient.get(...) overload:

enter image description here

However, the following is choosing a different overload, and I have no idea how to fix it:

enter image description here

Is this because I'm declaring the private options field incorrectly? I can't find in the API docs a better/correct way of declaring it so that the correct overload will be chosen successfully. Can someone please help me make my code choose the correct (generic Observable<T>) overload for HttpClient.get(...)?


Solution

  • This is because you are declaring options with type any.

    By doing this, the compiler knows nothing about the interface/members of options, despite the fact that you instantiate its value with an object made of 2 properties.

    Refactor into this:

    export class Foo {
       private options = {headers: {...}, withCredentials: true};
       ....
    }
    

    Now the compiler can infer the type of options, instead of statically reading it.