pepsi-maniac
pepsi-maniac

Reputation: 105

Typescript generics take an object of type and return type method return type

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

Upvotes: 2

Views: 49

Answers (1)

tokland
tokland

Reputation: 67850

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();
}

Upvotes: 2

Related Questions