我有一个数据存储,想创建一个方法来从存储中加载数据。 存储包含不同类型(类)的数据。 假设我的商店包含(除其他外)作者类型的数据。 我想加载 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;
}
关于 typescript 泛型 : return instance of class parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50851045/