L
L
Lancelot2021-10-11 12:17:43
typescript
Lancelot, 2021-10-11 12:17:43

How to make a method generic?

public getPayerTypes(): Observable<PayerType[]> {
    return this.http.get<PayerTypes>('getPayerTypes')
      .pipe(
        pluck('data'),
        catchError(this.handleError)
      );
  }


Here's something that doesn't work:
private httpGet<T, K>(url: string): Observable<T> {
    return this.http.get<PayerTypes>('getPayerTypes')
      .pipe(
        pluck('data'),
        catchError(this.handleError)
      );
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-10-11
@Aetae

What for? You explicitly indicate that the result is Observable<PayerTypes>. It cannot be anything else, and it does not depend on anything. Why there url?
Or maybe you mean something like this:

type Urls = {
    getPayerTypes: PayerTypes;
    getNPCTypes: NPCTypes;
}

private httpGet<K extends keyof Urls>(url: K): Observable<Urls[K]> {
  return this.http.get<Urls[K]>(url)
    .pipe(
      pluck('data'),
      catchError(this.handleError)
    );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question