Microsoft/TypeScript

Using nullish coalescing with untyped field in constructor trigger TS7022

Open

#55,013 创建于 2023年7月13日

在 GitHub 查看
 (1 评论) (0 反应) (0 负责人)TypeScript (6,726 fork)batch import
Domain: check: Type InferenceHelp WantedPossible Improvement

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

Bug Report

Using nullish coalescing in a constructor to initialize a class member with no type annotation will result in a TS7022 error.

🔎 Search Terms

nullish, coalescing, 7022, ??, and ts7022

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about nullish coalescing and type inference.

⏯ Playground Link

Playground link with relevant code

💻 Code

export class Node {
  #parent

  #children = new Children(this)

  constructor (parent?: Node | null | undefined) {
    // Remove `??` and the code after and the code compiled. Now #parent is undefined which is not desired.
    this.#parent = parent ?? null
  }

  get parent () { return this.#parent }

  get children () { return this.#children }
}

export class Children {
  #parent
  #head
  #tail

  constructor (parent: Node) {
    this.#parent = parent
    this.#head = new Node(parent)
    this.#tail = new Node(parent)
  }
}

🙁 Actual behavior

Attempting to compile the example code results in a TS7022 error: '#parent' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

🙂 Expected behavior

The code should compile and #parent should be typed as Node | null.

贡献者指南