Angular 5's HttpClient: What arguments does toPromise() accept?

Viewed 3674

If I try to return a promise of a specific type like this:

public myMethod(): Promise<MyType> {
  return this.httpClient.get('/my/url').toPromise();
}

...I get an error that the return type Promise<Object> does not match the expected type Promise<MyType>. That's easy enough to fix by casting the result or by doing this:

public myMethod(): Promise<MyType> {
  return this.httpClient.get<MyType>('/my/url').toPromise();
}

There's another option, however, to provide an optional argument to the toPromise() function. My IDE says the type of the argument is either "PromiseCtor: PromiseConstructorLike" or "PromiseCtor: typeof Promise".

public myMethod(): Promise<MyType> {
  return this.httpClient.get('/my/url').toPromise(???);
}

I can't figure out what syntax would satisfy the ??? above, however.

Any ideas about what can be filled in as a valid argument here?

2 Answers

You need to specify the type in the get method get<MyType>:

public myMethod(): Promise<MyType> {
   return this.httpClient.get<MyType>('/my/url').toPromise();
}
public async myMethod(): MyType {
  return await <MyType>this.httpClient.get('/my/url').toPromise();
}
Related