简体   繁体   English

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

[英]Enforcing type with generics in typescript and sequelize

I have an abstract service which is taking a repository in its constructor and getting data with Sequelize. 我有一个抽象服务,该服务在其构造函数中使用一个存储库,并使用Sequelize获取数据。 The abstract service looks like this: 抽象服务如下所示:

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

where T is the repository type: 其中T是存储库类型:

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

UserInfosModel is a sequelize @Model class. UserInfosModel是一个@Model续集类。

Now this works fine, but the only thing is that I wish to enforce the type to 现在这可以正常工作,但唯一的是我希望将类型强制为

_repo _repo

with a generic T rather than use any. 使用通用T而不是使用任何T。 The problem is that the compiler won't recognise T as UsersInfosRepository and won't find the method findId. 问题在于,编译器不会将T识别为UsersInfosRepository,也不会找到方法findId。 Has anyone got any suggestion on how to enforce the generic? 有没有人对如何执行通用有任何建议?

Cheers 干杯

So in the end I found the solution 所以最后我找到了解决方案

I changed the abstract BaseRepository into an interface: 我将抽象的BaseRepository更改为一个接口:

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

and edited the BaseService to accept: 并编辑了BaseService以接受:

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

Where T is any Repository and U is any model. 其中T是任何存储库,而U是任何模型。

export class UsersService extends BaseService<UsersInfosRepository, UserInfosModel>

hopefully this will be of help to anyone who like me struggled to find a solution including generics and sequelize. 希望这将对像我这样努力寻找包括泛型和续集在内的解决方案的所有人有所帮助。

You want to use <T extends Class> : 您要使用<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)))
    )
  }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM