我在代码中有这个:
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() 上给我一个错误。
文件:“沙盒.ts”
严重性:“错误”
消息:'类'Thingamajigger'错误地实现了接口(interface)'ThingKeeper'。
属性“getThings”的类型不兼容。
类型 '() => ThirdThing[]' 不能分配给类型 '() => T[]'。
类型“ThirdThing[]”不可分配给类型“T[]”。
类型“ThirdThing”不可分配给类型“T”。
在:'14,7'
来源:'ts'
代码:'2420'
这不应该工作吗?
感谢您的任何反馈。
最佳答案
如果您查看类型检查器报告的错误消息,很明显发生了什么:
() => ThirdThing[]
不能分配给 <T extends OneThing>() => T[]
ThirdThing[]
不能分配给 T[]
ThirdThing
不能分配给 T
类型
ThirdThing
和 T
不相关,例如,如果您考虑这样的层次结构: OneThing
/ \
T ThirdThing
因此,编译器说它不能确定地分配。解决方案是关联
T
和 ThirdThing
通过 ThingKeeper
类(class):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>();
}
}
关于typescript - 实现编译器不跟随的链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48670778/