short: Having a method that returns a http call (get, put, whatever), determine the type of the items returned, using typescript types?
On TypeScrpt level, a promise is a generic type. It carries on the type of the message you expect, e.g. IPromise<T>
. This way you can define that a method returns a promise of type Promise<number[]>
which basically returns a promise that resolves with a list of numbers. Thanks to this, you make typescript even more powerful.
You can do the same with Observables (RxJS). Simple, we've got Observable<T>
(just take a look at Observable.d.ts
in npm:rxjs
). Each item you expect in this stream is of type T (this is the subscribe
callback parameter - has to be - TypeScript checks this for you).
Angular
Going back to Angular, the HTTP module wraps Observables. It doesn't return values immediately, but emits http calls with HTTP-related stuff (status, status text, url, etc), not just the value. In http's .d.ts, http.get, put, post, etc return Observable<Response>
, where Response
is the Angular built-in wrapper for HTTP call. But I see I lose the possibility to predefine the type of what a HTTP is supposed to return.
question is: is there a possibility in angular http calls to predefine what type is the http-call/observable return? Something like Observable<User>
where User
is just my application interface.