jeudi 28 avril 2022

How to get advantage of types when having astract DAO class

So imagine that we have DAO interface that have the structure like this:

class interface UserDao<T> {
  findOne(query: any, projection: any): Promise<T>;
  findAll(query: any, projection: any): Promise<T[]>;
  create(item: any): Promise<T>;
  update(item: any): Promise<T>;
  delete(query: any): Promise<boolean>;
}

and we have a mongoDB implementation like this:

class MongoUserDao implements UserDao<User> {
  findOne(query: FilterQuery<User>, projection: ProjectionQuery<User>): Promise<User>;
  findAll(query: FilterQuery<User>, projection: ProjectionQuery<User>): Promise<User[]>;
  create(item: User): Promise<User>;
  update(item: User): Promise<User>;
  delete(query: FilterQuery<User>): Promise<boolean>;
}

and method (to be platform agnostic we are using the interface)

async function makeSomeChangesToUser(userDao: UserDao) {}

Problem: As we see, the interface that we are using in the function limits IntelliSense to type-hint the types of the parameters to any and makes MongoUserDao types useless. If we swap it to userDao: MongoUserDao we are not platform-agnostic anymore, and UserDao is useless. How can I make it platform-agnostic and still get the advantage of the types?

Aucun commentaire:

Enregistrer un commentaire