在打字稿中使用泛型强制执行类型并进行后续处理

时间:2019-05-10 23:58:38

标签: typescript typescript-generics sequelize-typescript

我有一个抽象服务,该服务在其构造函数中使用一个存储库,并使用Sequelize获取数据。抽象服务如下所示:

export abstract class BaseService<T> {

  public constructor(private _repo: any) {

  }
  public findById(id: string) {
    return this._repo.findById(id).pipe(
      map(res => Response.ok(res)))
    )
  }
}

其中T是存储库类型:

export class UsersInfosRepository extends BaseRepository<UserInfosModel>{
  public findById(id: string): Observable<UserInfosModel | null> {
    return from(UserInfosModel.findById(id));
  }
}

UserInfosModel是@Model类的续集。

现在这可以正常工作,但唯一的事情是我希望将类型强制为

  

_repo

使用通用T而不是使用任何T。问题在于,编译器不会将T识别为UsersInfosRepository,也不会找到方法findId。有没有人对如何执行通用有任何建议?

欢呼

2 个答案:

答案 0 :(得分:1)

所以最后我找到了解决方法

我将抽象的BaseRepository更改为一个接口:

export interface IBaseRepository<T> {
  findById(id: string): Observable<T | null>;
}

并编辑BaseService以接受:

export abstract class BaseService<T extends IBaseRepository<U>, U> 

其中T是任何存储库,而U是任何模型。

export class UsersService extends BaseService<UsersInfosRepository, UserInfosModel>

希望这对像我这样努力寻找包括泛型和续集的解决方案的人有所帮助。

答案 1 :(得分:0)

您要使用<T extends Class>

export abstract class BaseService<T extends UsersInfosRepository> {

  public constructor(private _repo: T) {

  }
  public findById(id: string) {
    return this._repo.findById(id).pipe(
      map(res => Response.ok(res)))
    )
  }
}

有关更多信息: https://www.typescriptlang.org/docs/handbook/generics.html

相关问题