I'm working on a typescript project and, at some point, I need to collect the FindOneOrFailOptions parameter from MikroORM in advance.
The code is far more complicated but I've managed to replicate the issue with fewer lines.
While this code works without a problem:
class ProviderRepository {
public async findOneByUrl(url: string): Promise<Provider> {
const repository = /* is of type EntityRepository<Provider> */
return await repository.findOneOrFail({ url }, { populate: ['profile'] });
}
}
The following one fails by raising TS2345: Argument of type '{ populate: string[]; }' is not assignable to parameter of type 'FindOneOrFailOptions<Provider, string>'.:
class ProviderRepository {
public async findOneByUrl(url: string): Promise<Provider> {
const repository = /* is of type EntityRepository<Provider> */
const options = { populate: ['profile'] };
return await repository.findOneOrFail({ url }, options);
-------
}
}
Well, sure enought the solution should be to declare options as FindOneOrFailOptions<Provider, string>. However, if I do this, then it raises TS2322: Type 'string' is not assignable to type 'never'.:
class ProviderRepository {
public async findOneByUrl(url: string): Promise<Provider> {
const repository = /* is of type EntityRepository<Provider> */
const options: FindOneOrFailOptions<Provider, string> = { populate: ['profile'] };
---------
return await repository.findOneOrFail({ url }, options);
}
}
And at this point I'm a bit lost as how to proceed.
I presume the never in there comes from the function declaration:
class EntityRepository<T extends AnyEntity<T>> {
findOneOrFail<P extends string = never>(where: FilterQuery<T>, options?: FindOneOrFailOptions<T, P>): Promise<Loaded<T, P>>;
}
However even if I use this function like repository.findOneOrFail<string>(...) it still produces the same error.
I reckon there must be some sort of auto-casting as if I inline the parameter, even without the <string>, it happy takes it without a problem. This tells me that I have not nailed the exact type that it is expecting but I'm a bit clueless as per what this type could be.
How can I have the options parameter declared in advance without any issue? Many thanks!