我在代码中有这个:
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>();
}
}
文件:'Sandbox.ts' 严重性:'错误' 消息:'Class'Thingamajigger'错误地实现了接口'ThingKeeper'。 属性'getThings'的类型是不兼容的。 输入'()=&gt; ThirdThing []'不能分配给'()=&gt;类型T []”。 类型'ThirdThing []'不能分配给'T []'。 类型'ThirdThing'不能分配给'T'类型。' at:'14,7' 来源:'ts' 代码:'2420'
不应该这样吗?
感谢您的反馈。
答案 0 :(得分:1)
如果你查看类型检查器报告的错误消息,很明显发生了什么:
() => ThirdThing[]
无法分配给<T extends OneThing>() => T[]
ThirdThing[]
无法分配给T[]
ThirdThing
无法分配给T
类型ThirdThing
和T
不相关,例如,如果您考虑这样的层次结构:
OneThing
/ \
T ThirdThing
因此,编译器说无法确定它。解决方案是通过T
类关联ThirdThing
和ThingKeeper
:
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>();
}
}