I'm trying to assign a generic type to another as default and return the assignee generic type in a function on an abstract class. I wanted it to be totally straightforward for the extended class for override it using the default value with no success.
This is a part (reduced) of my abstract class:
export abstract class ServicioRest <T> {
public listarPorId<K = T>(entidad?: T): Promise<K> {
return new Promise<K>((resolve: Function, reject: (error: any) => void): void => {
//some code
});
}
}
And these are some ways I've tried to create my extended class. Just the last two (4 and 5) worked out:
1)
class EntityService extends ServicioRest<IEntity> {
public listarPorId(entidad?: IEntity): Promise<IEntity> {
return super.listarPorId(entidad);
}
}
2)
class EntityService extends ServicioRest<IEntity> {
public listarPorId<IEntity>(entidad?: IEntity): Promise<IEntity> {
return super.listarPorId(entidad);
}
}
3)
class EntityService extends ServicioRest<IEntity> {
public listarPorId(entidad?: IEntity) {
return super.listarPorId(entidad);
}
}
4)
class EntityService extends ServicioRest<IEntity> {
public listarPorId<K=IEntity>(entidad?: IEntity): Promise<K> {
return super.listarPorId(entidad);
}
}
5)
class EntityService extends ServicioRest<IEntity> {
public listarPorId<K>(entidad?: IEntity): Promise<K> {
return super.listarPorId(entidad);
}
}
The ones that don't work make the compiler alert on this error:
ERROR in src/app/modules/rest/models/servicio-rest.spec.ts(31,16): error TS2416: Property 'listarPorId' in type 'EntityService' is not assignable to the same property in base type 'ServicioRest'.
Type '(entidad?: IEntity...' is not assignable to type '<K = IEntity>
(entidad: IEntity...'.
Type 'Promise<IEntity>
' is not assignable to type 'Promise<K>
'.
Type 'IEntity' is not assignable to type 'K'.
Although the last two work out, I don't like them because I can't restrict K to be IEntity. Is there any way to achive that restriction?