gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:53:56 25 4
gpt4 key购买 nike

我在代码中有这个:

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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com