typescript - 实现编译器不跟随的链

标签 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() 上给我一个错误。

文件:“沙盒.ts”
严重性:“错误”
消息:'类'Thingamajigger'错误地实现了接口(interface)'ThingKeeper'。
属性“getThings”的类型不兼容。
类型 '() => ThirdThing[]' 不能分配给类型 '() => T[]'。
类型“ThirdThing[]”不可分配给类型“T[]”。
类型“ThirdThing”不可分配给类型“T”。
在:'14,7'
来源:'ts'
代码:'2420'

这不应该工作吗?

感谢您的任何反馈。

最佳答案

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

  • () => ThirdThing[]不能分配给 <T extends OneThing>() => T[]
  • ThirdThing[]不能分配给 T[]
  • ThirdThing不能分配给 T

  • 类型ThirdThingT不相关,例如,如果您考虑这样的层次结构:
       OneThing
      /       \ 
     T       ThirdThing
    

    因此,编译器说它不能确定地分配。解决方案是关联 TThirdThing通过 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/

    相关文章:

    visual-studio - TypeScript - Visual Studio 2015 Intellisense 找不到模块

    c++ - 将 python 与 c++ 接口(interface)

    c++ - 错误 1 ​​错误 C2143 : syntax error : missing ';' before '<class-head>'

    c++ - 如何修复 Mac 上的 clang libc++ 错误 : calling private constructor

    java - Java : Code too large for Oracle's javac is not so for Eclipse

    javascript - object.assign 不复制函数

    reactjs - 状态改变时对话框播放动画

    java - 如何将泛型接口(interface)实现为非泛型类 Java

    javascript - 如何使用 Angular 编辑器在光标位置插入文本

    Java:在没有重复代码的情况下处理多个复杂接口(interface)