TypeScript Using nullish coalescing with untyped field in constructor trigger TS7022

42fyovps  于 9个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(138)

Bug报告

在构造函数中使用空值合并来初始化一个没有类型注解的类成员将导致TS7022错误。

🔎 搜索词

nullish , coalescing , 7022 , ?? , 和 ts7022

🕗 版本与回归信息

  • 我尝试了每个版本,发现这种行为都存在,我也查阅了关于空值合并和类型推断的FAQ条目。

⏯ Playground链接

带有相关代码的Playground链接

💻 代码

  1. export class Node {
  2. #parent
  3. #children = new Children(this)
  4. constructor (parent?: Node | null | undefined) {
  5. // Remove `??` and the code after and the code compiled. Now #parent is undefined which is not desired.
  6. this.#parent = parent ?? null
  7. }
  8. get parent () { return this.#parent }
  9. get children () { return this.#children }
  10. }
  11. export class Children {
  12. #parent
  13. #head
  14. #tail
  15. constructor (parent: Node) {
  16. this.#parent = parent
  17. this.#head = new Node(parent)
  18. this.#tail = new Node(parent)
  19. }
  20. }

🙁 实际行为

尝试编译示例代码会导致TS7022错误: '#parent' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

🙂 预期行为

代码应该能够编译,并且 #parent 应该被类型化为 Node | null

ghg1uchk

ghg1uchk1#

这是一个与我在这里诊断的问题非常相似的问题(我们在这里的代码路径几乎完全相同,只是问题的起源略有不同)
问题在于,这个初始化器中的二元表达式在这里创建了一个联合类型(左类型和右类型的联合),而这个联合是子类型约简的主题。这反过来要求 parent 的属性,并遇到了一个循环。
这个特定的例子可能可以避免,因为右边的类型是 null ,左边的类型不是空值,但其他提到的问题表明还有其他类似的情况,这些情况都无法帮助我们。希望有一个更智能的修复方法,但我没有想法。

相关问题