Multitut
Multitut

Reputation: 2169

How to use a type on map operator in typescript?

Basically, I am trying to use HttpClient instead of Http on all my calls, so I created an interface to be able to access some properties of the response, it is working fine for most of my calls; but the thing is that I have a typeahead with this code:

const URL = 'https://maps.google.com/maps/api/geocode/json';
this.searchField = new FormControl();
this.results$ = this.searchField.valueChanges
    .debounceTime(500)
    .switchMap(query => this.http.get(`${URL}?address=${query}`))
    .map(response => response)
    .map(response => response.results);

I tried to assign my interface called APIResponse to response on the last two lines, like this: .map(response:APIResponse => ...), but it obviously throws a syntax error.

Where should I include the type for response? Or how could I change my code to do so?

Thanks in advance.

Upvotes: 1

Views: 1013

Answers (2)

meriton
meriton

Reputation: 70564

Personally, I'd do:

.map(response => response.json() as ApiResponse)
.map(response => response.results);

BTW, if you were to use the new HttpClient introduced in angular 4.3, you wouldn't need to convert to JSON manually and could simply write:

this.httpClient.get<ApiResponse>(`${URL}?address=${query}`
    .map(response => response.results);

Upvotes: 4

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657496

If you add a type you need to use ():

.map((response:APIResponse) => ...)

Upvotes: 2

Related Questions