Type inference with generic custom repository #7392
-
|
I am following documentation to add a generic custom repository to my MikroORM configuration. It appears that the type inference is not working in this case. Below is a small repro for the issue I am facing - import {
defineConfig,
defineEntity,
EntityRepository,
MikroORM,
p,
type InferEntity,
} from '@mikro-orm/postgresql';
class BaseRepository<Entity extends object> extends EntityRepository<Entity> {
exists() {
// implementation here
return (Math.random() * 10) % 2;
}
}
const User = defineEntity({
name: 'User',
tableName: 'users',
properties: {
id: p.uuid().primary(),
email: p.string(),
},
});
type User = InferEntity<typeof User>;
const config = defineConfig({
dbName: 'repro',
entities: [User],
entityRepository: () => BaseRepository,
});
async function main() {
const orm = await MikroORM.init(config);
const repo = orm.em.getRepository(User);
await repo.findAll();
// Expected: global `entityRepository` should make this available.
// Actual: TS error - Property 'exists' does not exist on type ...
await repo.exists();
}
void main();I am using - I will be very helpful if someone points out the correct way of doing it. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
ORM config is not relevant on type level, you need to specify the repository in your entity definition, that's what add the type level hint. For a generic base repository, it would make sense to define a base entity that does this. The section above the one you mentioned shows how. edit: I'll adjust the docs about this |
Beta Was this translation helpful? Give feedback.
-
|
The global To get const User = defineEntity({
name: 'User',
tableName: 'users',
repository: () => BaseRepository, // add this
properties: {
id: p.uuid().primary(),
email: p.string(),
},
});With that change, You can still keep For reference, if you're using the decorator-based entity style the equivalent looks like this: @Entity({ repository: () => BaseRepository })
class User {
[EntityRepositoryType]?: BaseRepository<User>; // manual type hint needed for decorators
// ...
}The |
Beta Was this translation helpful? Give feedback.
ORM config is not relevant on type level, you need to specify the repository in your entity definition, that's what add the type level hint. For a generic base repository, it would make sense to define a base entity that does this. The section above the one you mentioned shows how.
edit: I'll adjust the docs about this