0

EDIT: a minimal example is available here here

I'm using TypeScript with TypeORM library. This is the "base" Repository generic definition:

class Repository<Entity extends ObjectLiteral> {
  find(conditions?: FindConditions<Entity>): Promise<Entity[]>;
}

If I try to extend this class, passing Bank class as Entity, it works as expected (I get auto-completion in find method):

class Bank {
  name: string;
}

class BankRepository extends Repository<Bank> {
  public test():void  {
    this.find({ name: 'foo' }); // OK!
  }
}

However, If I try to make my generic, with BankModel abstract class:

abstract class BankModel {
  foo: string;
}

class BankRepository<E extends BankModel> extends Repository<E> {
  test(foo: string): void {
    this.find({ foo: foo }); // KO!!! 
  }
}

The error is:

Argument of type '{ foo: string; }' is not assignable to parameter of type 'FindConditions'.ts(2345),

The declaration of FindConditions<E> is:

declare type FindConditions<T> = {
  [P in keyof T]?: FindConditions<T[P]> | FindOperator<FindConditions<T[P]>>;
};

So.. why it doesn't work?

enter image description here

gremo
  • 47,186
  • 75
  • 257
  • 421
  • I don't know typeorm so I can't reproduce this, but my hunch is that this will be something like [this question](https://stackoverflow.com/questions/46980763/why-cant-i-return-a-generic-t-to-satisfy-a-partialt), where it is invalid to assume that `FindConditions` is assignable to `FindConditions` for all possible `E extends BankModel`; that is, there might be some subtype `E` of `BankModel` for which `{foo: foo}` is incompatible with `FindConditions`. If you remove the question's dependency on typeorm and post a [mcve] I might be able to answer. Otherwise, good luck! – jcalz Sep 07 '19 at 23:45
  • @jcalz why it's invalid to assume that? If E extends BankModel, the public property "foo" should be there. – gremo Sep 08 '19 at 10:12
  • Did you read the linked question? – jcalz Sep 08 '19 at 10:31
  • @jcalz I made a minimal example without using Typeorm library. Can you help me understand why it doesn't work? – gremo Sep 11 '19 at 07:23
  • All the code should be in the question text and not only in an external link, as described in [the guidelines for how to ask a good question](https://stackoverflow.com/help/how-to-ask). If you do provide a link it should be to a web IDE so that others can see what's happening without having to install anything in their own environment. I doubt anyone would be willing to `npm install` something onto their machine just to answer a question... in the ideal case, someone could drop the code into a [standalone IDE](http://www.typescriptlang.org/play/#code/Q) and reproduce. Good luck again! – jcalz Sep 11 '19 at 13:10
  • @jcalz nevermind, solved, thanks! – gremo Sep 11 '19 at 14:20

1 Answers1

0

I turns out what was a Typescript bug. I works with version 3.6.3.

gremo
  • 47,186
  • 75
  • 257
  • 421