Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

type inference for a angular util function

I am currently working in angular, my http client returns Observable<HttpResponse<T>>. I am trying to create a util function that wraps this and returns a Promise<T>

  const response = await baseResponseHandler(this.api.getAccountInfo('response'); //response is unknown

here is the util function:

export async function baseResponseHandler<
  K,
  T extends Observable<HttpResponse<K>>,
>(arg: T): Promise<K> {
  const value = await firstValueFrom(arg); //rxjs Observable -> Promise
  if (value.ok) {
    return value.body;
  }
  return value.body;
}

Why is it not infering the type correctly?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

export async function baseResponseHandler<K>(
 arg: Observable<HttpResponse<K>>
): Promise<K> {
  const value = await firstValueFrom(arg);
  if (value.ok) {
    return value.body;
  }
  return value.body;
}

Now when you call it

const response = await baseResponseHandler<myType>(this.api.getAccountInfo('response');

I hope this helps you. Cheers 🥂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading