Reputation: 21
Why is typecasting the Observable a standard? What is happening under the hood? It is solely for compile time assertion?
Here is an example of:
getAnything = (): Observable<Data> => {
return this.httpclient.get('https://my_api.com')
.map(this.handleSuccess)
.catch(this.handleError);
}
And why not this :
getAnything = (): {
return this.http.get('https://my_api.com')
.map(this.handleSuccess)
.catch(this.handleError);
}
HTTP Client returns Observable, but why do we want to typecast Observable, what are the pros for this?
I tried searching Angular documentation however was not able to find the specific reason for this
Upvotes: 2
Views: 306
Reputation: 443
Explicitly adding the return type of a method from angular's HTTP call doesn't really perform any type casting since without a specified type, this.http.get
would return an Observable<any>
.
This means that an explicit return type declaration with TypeScript will not guarantee that the data sent back by the http call would "conform" to the type that your supposedly returning - it's just the nature of JavaScript. Like the other answer said, it's just for compile-time assertion.
My opinion is that (my own, not a standard, but I find to be quite helpful) is to explicitly cast the data into whatever type you want it to be through the map
operator that you seem to be already using.
http.get('some/api')
.pipe(
map(data => {
const result = new Data();
result.prop1 = data.prop1;
result.prop2 = data.prop2;
return result;
})
)
This makes sure that the data returned is not just an anonymous JSON object, and your method is now implicitly typed. This makes run-time type-inconsistency easier to catch too by failing on class instance creation if certain properties does not exist on the JSON object.
If you're using an interface as your type however, then this wouldn't be all that helpful since, as mentioned earlier, type assertion only happens at compile time.
Upvotes: 1
Reputation: 3593
It's for compile time assertion.
Without it, the compiler will know that it's returning an Observable
of something.
Being more specific will help make sure you are returning what you think you are to the best of TypeScript's ability. If you forgot the word return for example, it would complain that you were not returning anything.
Upvotes: 1