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?