[英]Typescript Generics: return instance of class parameter
我有一个数据存储并想创建一种方法来从存储加载数据。 存储包含不同类型(类)的数据。 假设我的商店包含(除其他外)作者类型的数据。 我想加载 id 为 1 的作者:
const author1 = store.loadById(Author, 1);
现在我如何使用泛型让 TS 编译器知道 author1 是 Author 的一个实例?
我现在有
public loadById<T>(entityClass: T, id: number): T {
const entity;
// logic to load the entity ...
return entity;
}
但这是错误的,因为现在 TSC 认为我的方法返回一个 entityClass 而不是 entityClass 的一个实例。 那么我如何指定方法的返回类型才能让 author1 成为 Author 的一个实例呢?
您将类Author
传递给方法,而不是Author
类的实例,因此参数需要是构造函数签名:
public loadById<T>(entityClass: new () => T, id: number): T {
const entity = new entityClass();
// logic to load the entity ...
return entity;
}
const author1 = store.loadById(Author, 1); // will be of type Author
或者,如果您有构造函数的参数,则可以在签名中指定这些参数:
public loadById<T>(entityClass: new (data: any) => T, id: number): T {
const entity = new entityClass(null as any); // pass data
// logic to load the entity ...
return entity;
}
对于那些想要传递类并返回类的实例的人
function newInstance<T extends new () => InstanceType<T>>(TheClass: T): InstanceType<T> {
return new TheClass();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.