【问题标题】:Typescript Generic type makes compilation errorTypescript Generic 类型导致编译错误
【发布时间】:2018-02-14 19:11:38
【问题描述】:

我有一个案例,我需要在不同类别的项目之间获取层次结构。它们都扩展了同一个类 ItemExt。

我正在使用 Typescript 2.4.2

这是我的代码:

export class ItemCollection<ItemFather extends ItemExt, ItemSon extends ItemExt> {

  constructor(private typeClass: { new (): ItemSon; }, parent? : ItemFather, fatherColl? : ItemCollection<ItemFather, ItemSon>){
  }

  public GetSub<ItemSon extends ItemExt, ItemSub extends ItemExt>(typeClass: { new (): ItemSub; }, obj : ItemSon) {
      return new ItemCollection<ItemSon, ItemSub>(typeClass, obj, this);
  }
}

export abstract class ItemExt {
  public Id : string;
}

但是编译器在“this”的方法“GetSub”中给我一个错误:

“this”类型的参数不能分配给类型参数 '项目集合'。类型“ItemCollection”不可分配给类型“ItemCollection”。类型“ItemFather”不可分配给类型“ItemSon”。类型 'ItemExt' 不可分配给类型 'ItemSon'。

我认为这只是语法或声明问题,因为当我使用 eval("this") insted of "this" 时,它按预期工作。

有人可以帮我避免没有 eval 的编译错误吗?

提前致谢

【问题讨论】:

  • 请不要将事物命名为type。不要像有棱有角的那样迷惑很多人

标签: typescript generics compilation


【解决方案1】:

问题是构造函数中fatherColl的类型是ItemCollection&lt;ItemFather, ItemSon&gt;,所以当你调用new ItemCollection&lt;ItemSon, ItemSub&gt;(...时,它强制第三个参数的类型是ItemCollection&lt;ItemSon, ItemSub&gt;,因为你已经定义了这样的类型传入的父集合上的泛型需要与正在创建的ItemCollection 的泛型匹配。

所以基本上你是在传递ItemCollection&lt;ItemFather, ItemSon&gt;,但告诉它应该期待类型ItemCollection&lt;ItemSon, ItemSub&gt;

这两个定义不匹配,因此它正确地表示您有类型错误。

如果您只是 eval,这会起作用,因为这样的类型检查不是 Javascript 的一部分,而纯粹是在 TypeScript 的领域中,并且通过将所有内容放在 eval 调用中,您正在删除类型检查。

【讨论】:

  • 感谢您的回复,我明白了。那么我应该改变什么来让 il 在没有 eval 的情况下工作?
猜你喜欢
  • 1970-01-01
  • 2015-10-03
  • 2022-12-14
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 1970-01-01
相关资源
最近更新 更多