adaba
adaba

Reputation: 384

How to type the method of a subclass extending an abstract generic class

Considering my base class:

export abstract class BaseClass<T> {
  BASE_URL = CONFIG.BACKEND_URL
  protected constructor(protected http: HttpClient) {
    this.BASE_URL = `${this.BASE_URL}${this.getModelURL()}`
  }
  all<T>(): Observable<T[]> {
    return this.http.get<T[]>(this.BASE_URL)
      .pipe(map((response: any) => response.data))
  }
}
export class TagService extends BaseAPIService<Tag> {
  constructor(protected http: HttpClient) {
    super(http)
  }
}

When I call my service through this.tagService.all().subscribe(tags => this.tags = tags)

I get Type 'unknown[]' is not assignable to type 'Tag[]'.

which is solved by typing this.tagService.all<Tag>().subscribe(tags => this.tags = tags)

I don't understand why I have to write the type again to all<Tag>(), is it the only way to get rid of that error ?

Upvotes: 0

Views: 131

Answers (1)

Ga&#235;l J
Ga&#235;l J

Reputation: 15070

When defining all with a generic type T, you are hiding the generic type T of the class.

You wrote the same as:

abstract class BaseClass<T> {
  all<U>(): Observable<U[]> { ... }
}

If you want to reuse the type T of the class, no need to declare the method as generic, it's the class that is:

abstract class BaseClass<T> {
  all(): Observable<T[]> { ... }
}

Upvotes: 1

Related Questions