Typescript Generics:返回类参数的实例

时间:2018-06-14 06:35:41

标签: typescript generics

我有一个数据存储,想要创建一个从商店加载数据的方法。 商店包含不同类型(类)的数据。 让我们说我的商店包含(以及其他)类型作者的数据。 我想加载id为1的作者:

const author1 = store.loadById(Author, 1);

现在我如何使用泛型来让TS编译器知道author1是作者的实例?

我现在有

public loadById<T>(entityClass: T, id: number): T {
        const entity;
        // logic to load the entity ...
        return entity;
    }

但这是错误的,因为现在TSC认为我的方法返回entityClass而不是entityClass的实例。 那么我如何指定方法的返回类型以使author1成为作者的实例?

2 个答案:

答案 0 :(得分:4)

您正在将类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;
}

答案 1 :(得分:2)

对于那些想要传递一个类并返回一个类的实例的人

function newInstance<T extends new () => InstanceType<T>>(TheClass: T): InstanceType<T> {
    return new TheClass();
}