【问题标题】:Typescript Generics: return instance of class parameter打字稿泛型:返回类参数的实例
【发布时间】:2018-06-14 06:35:40
【问题描述】:

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

【问题讨论】:

  • 你真的需要方法中的类吗?如果不是,loadById&lt;Author&gt;(1) 提供泛型类型。否则,我想你想要typeof T
  • @jonrsharpe typeof 不适用于泛型参数。
  • @TitianCernicova-Dragomir 啊,谢谢;我会回复说你需要一个new 签名,但是你已经写了那个答案!

标签: typescript generics


【解决方案1】:

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

【讨论】:

  • 感谢您的精彩回答!您能否添加一个示例,说明在最后一种情况下(使用数据)我应该如何调用 loadById 方法?以及数据是如何传递给 entityClass 实例的?现在代码是(null as any)。如何获取 loadById 中的数据?
  • @mvermand 您如何获取数据取决于您在做什么,我无法对此发表评论。一旦你在变量中有一些数据,你可以像调用任何其他构造函数一样调用entityClassnew entityClass(data)
【解决方案2】:

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

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

【讨论】:

  • 这适用于类,但不适用于“文字”函数。为什么?例如newInstance(function xyz() {})newInstance(function () {}),我得到Type '() =&gt; void' provides no match for the signature 'new (): any'
猜你喜欢
  • 2020-06-29
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 2022-11-11
相关资源
最近更新 更多