如何键入扩展抽象泛型类的子类的方法

阿达巴

考虑到我的基类:

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)
  }
}

当我通过以下方式调用我的服务时 this.tagService.all().subscribe(tags => this.tags = tags)

我得到 Type 'unknown[]' is not assignable to type 'Tag[]'.

这是通过输入解决的 this.tagService.all<Tag>().subscribe(tags => this.tags = tags)

我不明白为什么我必须再次将类型写入all<Tag>(),这是摆脱该错误的唯一方法吗?

盖尔J

all使用泛型类型定义T,您隐藏T了类的泛型类型

你写的一样:

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

如果你想重用T的类型,不需要将方法声明为泛型,它的类是:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章