【问题标题】:Why my generic of generic doesn't work as expected?为什么我的泛型不能按预期工作?
【发布时间】:2020-01-10 03:00:13
【问题描述】:

编辑:这里有一个最小的例子here

我将 TypeScript 与 TypeORM 库一起使用。这是“基础”Repository 通用定义:

class Repository<Entity extends ObjectLiteral> {
  find(conditions?: FindConditions<Entity>): Promise<Entity[]>;
}

如果我尝试扩展这个类,将Bank 类传递为Entity它按预期工作(我在find 方法中得到自动完成):

class Bank {
  name: string;
}

class BankRepository extends Repository<Bank> {
  public test():void  {
    this.find({ name: 'foo' }); // OK!
  }
}

但是,如果我尝试使用 BankModel 抽象类使 my 通用:

abstract class BankModel {
  foo: string;
}

class BankRepository<E extends BankModel> extends Repository<E> {
  test(foo: string): void {
    this.find({ foo: foo }); // KO!!! 
  }
}

错误是:

类型参数 '{ foo: string; }' 不可分配给“FindConditions”.ts(2345) 类型的参数,

FindConditions&lt;E&gt;的声明是:

declare type FindConditions<T> = {
  [P in keyof T]?: FindConditions<T[P]> | FindOperator<FindConditions<T[P]>>;
};

那么..为什么它不起作用?

【问题讨论】:

  • 我不知道 typeorm,所以我无法重现这个,但我的直觉是这将类似于 this question,其中假设 FindConditions&lt;BankModel&gt; 可分配给 @ 是无效的987654339@ 代表所有可能的E extends BankModel;也就是说,BankModel 中可能有一些子类型 E,其中{foo: foo}FindConditions&lt;E&gt; 不兼容。如果您删除问题对 typeorm 的依赖并发布 minimal reproducible example 我也许可以回答。否则,祝你好运!
  • @jcalz 为什么假设是无效的?如果 E 扩展了 BankModel,则公共属性“foo”应该在那里。
  • 你读过链接的问题吗?
  • @jcalz 我做了一个最小的例子,没有使用 Typeorm 库。你能帮我理解为什么它不起作用吗?
  • 所有代码都应该在问题文本中,而不仅仅是在外部链接中,如the guidelines for how to ask a good question 中所述。如果你确实提供了一个链接,它应该是一个 Web IDE,这样其他人就可以看到正在发生的事情,而无需在他们自己的环境中安装任何东西。我怀疑有人愿意在他们的机器上npm install 一些东西只是为了回答一个问题……在理想情况下,有人可以将代码放入standalone IDE 并复制。再次祝你好运!

标签: typescript typeorm typescript-generics


【解决方案1】:

我发现什么是 Typescript 错误。我使用 3.6.3 版本。

【讨论】:

    猜你喜欢
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2021-05-30
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多