0

I've two generic functions:

findOne<Entity>(cls: ClassType<Entity>, id: number): Promise<Entity>;
plainToClass<T, V>(cls: ClassType<T>, plain: V, options?: ClassTransformOptions): T;

How can I forward the template from findOne() to plainToClass() like in this case?

findOne<Entity>(cls: ClassType<Entity>, id: number): Promise<Entity> {
  return new Promise<Entity>(resolve => {
    resolve(plainToClass(cls /* here */, this.electronService.ipcRenderer.sendSync('findOne', cls.name, id)));
  });
}

Edit

Here is a full example: https://stackblitz.com/edit/typescript-lqnedb

4
  • 1
    What do you mean by "forward the template"? TypeScript's generics are not really templates as they exist in C++; there's a large enough mismatch that I'd suggest explicitly spelling out what you want to achieve without using template metaprogramming terminology. Also, please consider editing the code to constitute a minimal reproducible example as described by How to Ask. Right now there are too many missing declarations and syntax errors. (e.g., What is ClassType? What is ClassTransformOptions? What is this.electronService.ipRenderer.sendSync()? Do you want => instead of =?) Good luck!
    – jcalz
    Commented Jan 10, 2020 at 18:41
  • I mean does this call findOne(User, 4) call plainToClass(User /* <-- User here? */, ...)? I forgot to precise that I'm totally new to TS. I'll add a full working example. Thanks
    – didil
    Commented Jan 10, 2020 at 21:08
  • Yes, new Promise(r => r(foo(x))) calls foo(x). Have you tested it or tried to debug it? The issue in your linked code is not that plainToClass() is not being called; it's that it doesn't know how to turn createdAt into a Date, as described here.
    – jcalz
    Commented Jan 11, 2020 at 1:10
  • You got the point. I didn't know the plainToClass() issue with Date. Thanks!
    – didil
    Commented Jan 15, 2020 at 20:04

0

Browse other questions tagged or ask your own question.