简体   繁体   English

Typescript generics 采用 object 类型和返回类型方法返回类型

[英]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我需要制作一种方法,该方法采用 Model 的派生 class 并将其转换为保留通用 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

I assume you want the Model parameterized by Entity?我假设您想要由实体参数化的 Model? playground 操场

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM