1
getData(): Observable<A | B> {
  return this.http.get<A | B>(this.requestURL, {});
}

If I remove <A | B> syntax next to the get method, tslint emits an error saying: You can't bind Object to A or B so, I wound up adding the syntax without understanding what's going on with the syntax. I looked up Generics in Typescript and the syntax seems to be used to capture the type the user provide. What confuses me is that according to the source code of the get method in http module in Angular 5 which I'm currently using, get method declaration doesn't use generics(get method source code). Besides, if the error occurs due to the type, wouldn't return <Observable<A | B>>this.http.get(this.requestURL, {}) be correct?

To sum up, what's the point/purpose of using Generics syntax when calling a function like, get<T>() if the get method doesn't use the type information T in its declaration part?

Any insight would be appreciated!

1 Answer 1

1

You found the source for the deprecated Http module (@angular/http). You are using the new module (@angular/common/http), which does have a generic get method.

Using generic parameters on a method that does not define any is a compilation error, it has no meaning.

In the case of the get method, the type parameter is used to type the response. Not specifying the type parameter is an error in itself which can't be solved by casting (the cast <Observable<A | B>>this.http.get(this.requestURL, {}) is invalid because the compilation error is already triggered by the invocation of get which is missing it's type parameters)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.