i want to implement the generic repository/service pattern in this way
import { EntityTarget, FindOptionsWhere } from "typeorm";
import { AppDataSource as db } from "../database";
export const getAllSerivce = async <T>(
entity: EntityTarget<T>,
query?: FindOptionsWhere<T>
) => {
const repository = db.getRepository(entity);
const res = query ? await repository.findBy(query) : await repository.find();
return res;
};
but i got this error :
Argument of type 'EntityTarget' is not assignable to parameter of type 'EntityTarget'. Type '{ type: T; name: string; }' is not assignable to type 'EntityTarget'. Type '{ type: T; name: string; }' is not assignable to type '{ type: ObjectLiteral; name: string; }'. Types of property 'type' are incompatible. Type 'T' is not assignable to type 'ObjectLiteral'.ts(2345) generic.service.ts(5, 38): This type parameter might need an
extends ObjectLiteral
constraint.
CodePudding user response:
Since EntityTarget
or FindOptionsWhere
have a generic constraint on T
, you need to add that constraint to your function as well:
export const getAllSerivce = async <T extends ObjectLiteral>(
// ^^^^^^^^^^^^^^^^^^^^^^^
entity: EntityTarget<T>,
query?: FindOptionsWhere<T>
) => {
const repository = db.getRepository(entity);
const res = query ? await repository.findBy(query) : await repository.find();
return res;
};