Funkcja polimorficzna w typescript

0

Ma ktoś pomysł na mój problem? Jestem nadal trochę zielony w ts
Nest.js i mongoose, mamy kontroler i serwis. Kontroler wywołuje serwis w ten sposób:

 @Get()
 async findAll(): Promise<Array<Cat | Dog>> {
   return await this.petsService.findAll();
 }
 @Get('/cats')
 async findCats(): Promise<Cat[]> {
   return await this.petsService.findAll<Cat>('cat');
 }
 @Get('/dogs')
 async findDogs(): Promise<Dog[]> {
   return await this.petsService.findAll<Dog>('dog');
 }	

Natomiast findAll w serwisie wygląda tak:

async findAll<T = Cat|Dog>(petType?: 'cat' | 'dog'): Promise<T[]> {
   switch (petType) {
     case 'cat':
       return this.catModel.find().exec();
     case 'dog':
       return this.dogModel.find().exec();
     default:
       return [
         ...(await this.catModel.find().exec()),
         ...(await this.dogModel.find().exec()),
       ];
   }
 }

To nie działa, ts (trzeba zainstalować @types/mongoose) podkreśla w serwisie powyższą metodę z błędem

Type 'Cat' is not assignable to type 'T'.
            'Cat' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.

Chciałbym żeby findAll() była polimorficzna, tzn mogła zwracała różny typ (Cat albo Dog albo Cat|Dog) w zależności od parametru. Czy to jest możliwe? Co robię źle?

0

Ok wymyśliłem coś takiego,

async findAll(petType?: 'cat'): Promise<Cat[]>;
  async findAll(petType?: 'dog'): Promise<Dog[]>;
  async findAll(petType: 'cat' | 'dog'): Promise<Array<Cat|Dog>> {
    switch (petType) {
      case 'cat':
        return this.catModel.find().exec();
      case 'dog':
        return this.dogModel.find().exec();
      default:
        return [
          ...(await this.catModel.find().exec()),
          ...(await this.dogModel.find().exec()),
        ];
    }
  }

function overloading

0
async findDogs(): Promise<Dog[]> {
   return this.dogModel.find().exec();
}

async findCats(): Promise<Cat[]> {
   return this.catModel.find().exec();
}

async findAll(): Promise<(Cat|Dog)[]> {
   return Promise.all([this.findDogs(), this.findCats()]);
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1