Home > other >  Typescript generics take an object of type and return type method return type
Typescript generics take an object of type and return type method return type

Time:08-21

Take two base classes

interface Entity {}
interface Model {
  toEntity(): Entity;
}

I need to make a method that takes a derivied class of Model and converts it to entity preserving the generic class

function convert<T extends Model, J extends T['toEntity']>(model: T) { 
  return model.toEntity();
}

However this yields

Type Entity is not assignable to type J. J could be instantiated with an arbitrary type which could be unrelated to Entity

CodePudding user response:

I assume you want the Model parameterized by Entity? playground

interface Model<Entity> {
  toEntity(): Entity;
}

function convert<Entity>(model: Model<Entity>): Entity {
    return model.toEntity();
}
  • Related