Skip to content

How to setup a generic object mapping from entities to EntityRepository inference #1683

Answered by B4nan
ryankauk asked this question in Q&A
Discussion options

You must be logged in to vote

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 with unknown as a result. There are more issues in your code, like Entities[Key] should be Entities[k] I guess? Also I don't see a reason to use AnyEntity here.

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>

http…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@ryankauk
Comment options

Answer selected by B4nan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants