实现链没有跟随编译器

时间:2018-02-07 18:20:36

标签: typescript interface compiler-errors

我在代码中有这个:

interface OneThing {
}

interface AnotherThing extends OneThing {
}

interface ThirdThing extends AnotherThing {
}

interface ThingKeeper {
  getThings<T extends OneThing>(): T[];
}

class Thingamajigger implements ThingKeeper {
  getThings(): ThirdThing[] {
    return new Array<ThirdThing>();
  }
}
Typescript编译器在Thingamajigger中给出了getThings()的错误。

文件:'Sandbox.ts' 严重性:'错误' 消息:'Class'Thingamajigger'错误地实现了接口'ThingKeeper'。   属性'getThings'的类型是不兼容的。     输入'()=&gt; ThirdThing []'不能分配给'()=&gt;类型T []”。       类型'ThirdThing []'不能分配给'T []'。         类型'ThirdThing'不能分配给'T'类型。' at:'14,7' 来源:'ts' 代码:'2420'

不应该这样吗?

感谢您的反馈。

1 个答案:

答案 0 :(得分:1)

如果你查看类型检查器报告的错误消息,很明显发生了什么:

  • () => ThirdThing[]无法分配给<T extends OneThing>() => T[]
  • ThirdThing[]无法分配给T[]
  • ThirdThing无法分配给T

类型ThirdThingT不相关,例如,如果您考虑这样的层次结构:

   OneThing
  /       \ 
 T       ThirdThing

因此,编译器说无法确定它。解决方案是通过T类关联ThirdThingThingKeeper

interface OneThing {
}

interface AnotherThing extends OneThing {
}

interface ThirdThing extends AnotherThing {
}

interface ThingKeeper<T extends OneThing> {
  getThings(): T[];
}

class Thingamajigger implements ThingKeeper<ThirdThing> {
  getThings(): ThirdThing[] {
    return new Array<ThirdThing>();
  }
}