-
I'm wondering if I could get a bit of guidance on using generics mapping from entities to repository. Here's what I have. export const createDB2 = <
Entities extends { [k in Key]: AnyEntity<Entities[Key]> },
Key extends string = string
>(
entity: { [k in Key]: EntityName<Entities[Key]> }
) => {
const orm: MikroORM<MongoDriver> = {} as any;
return {} as {
[key in Key]: MongoEntityRepository<Entities[key]>;
};
};
const repos = createDB2({ MyEntity: MyEntity });
repos.MyEntity.findOne({});
// (property) MyEntity: MongoEntityRepository<AnyEntity<unknown>> however it works properly if i directly declare the types instead of inferring const repos = createDB2<{ MyEntity: MyEntity }, "MyEntity">({ MyEntity: MyEntity });
repos.MyEntity.findOne({});
// (property) MyEntity: MongoEntityRepository<MyEntity> |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Well but in your first example, you don't have the The code is quite messy, so instead of debugging it more, here is a different approach: type Ret<T> = { [k in keyof T]: T[k] extends EntityName<infer U> ? EntityRepository<U> : EntityRepository<unknown> };
function createDB<T>(map: T): Ret<T> {
return map as any;
}
const repos = createDB({ MyEntity: MyEntity });
repos.MyEntity.findOne();
// (property) MyEntity: EntityRepository<MyEntity> |
Beta Was this translation helpful? Give feedback.
Well but in your first example, you don't have the
Key
information anywhere, it will always fallback to the default value, so you end up withunknown
as a result. There are more issues in your code, likeEntities[Key]
should beEntities[k]
I guess? Also I don't see a reason to useAnyEntity
here.The code is quite messy, so instead of debugging it more, here is a different approach:
http…