microsoft / microsoft/TypeScript

Using nullish coalescing with untyped field in constructor trigger TS7022

オープン
#55,013 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

Domain: check: Type Inference Help Wanted Possible Improvement
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

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.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

リンクされた TypeScript Playground と、提供されている Node クラスおよび Children クラスを使って問題を再現します。TS7022 周辺で、型指定のない private フィールドと nullish coalescing をコンパイラーがどのように処理するかを追跡します。完了条件は、例がコンパイルされ、#parent がアノテーションなしで Node | null と推論されることです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
typescript
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
38/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。