typescript 泛型 : return instance of class parameter

标签 typescript generics

我有一个数据存储,想创建一个方法来从存储中加载数据。 存储包含不同类型(类)的数据。 假设我的商店包含(除其他外)作者类型的数据。 我想加载 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/

相关文章:

javascript - this 关键字在构造函数行为内的回调函数中使用

angular - activatedRoute 快照在 TS 类构造函数中不起作用

c# - 字典中结构键的值相等和类键的引用相等

javascript - 如何拦截非 JSON 的响应

javascript - 从 .ts 编写的简单 Angular2 应用程序调用/加载 .js 类和函数时遇到问题

angular - 通过 Angular2 路由器传递数据

多类型参数约束的 C# 泛型语法

java - 真正的 Java 泛型(模板)

具有泛型和继承的 java 抽象类 : Bound mismatch

java泛型方法调用转换错误