microsoft / microsoft/TypeScript

Static variable may be undefined when constructing an object of the same class

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

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

Awaiting More Feedback Suggestion
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

Bug Report

I'm not sure whether this may be a issue that can be fixed or just keep it as is "by design". I haven't found any other issues similar to this one here, at least with the search terms I tried (sorry if someone else already reported this 🙂).

🔎 Search Terms

static, undefined, uninitialized, constructor

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about static variables, variable order initialization, etc., but none of them seem to match this.

At the moment of writing this, TypeScript version is 4.2.3.

⏯ Playground Link

Playground Link

💻 Code
class A {
    public static readonly instance: A = new A();
    public static readonly constant: number = 1;
    
    public constructor() {
        console.log(A.constant, A.constant * 5);
        console.log(A.constant.toString());
    }
}
🙁 Actual behavior

When calling the constructor to initialize the static variable instance, A.constant is not yet initialized (it's undefined), so the constructor logs undefined, NaN.

In addition, A.constant.toString() gives a javascript execution error, which even in strict mode the compiler doesn't catch.

🙂 Expected behavior

The compiler could tell that constant has type number | undefined at that moment (manually changing the type of constantto number | undefined correctly yields a compiler error) or even rearrange the generated javascript to initialize first constant and then instance (which I think it may be more difficult in more complex scenarios).

Thank you very much!

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

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

はじめの一歩

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

調査の方向性

リンクされた TypeScript Playground の再現から始め、出力された JavaScript と報告された初期化順序を比較します。構築時に型チェッカーが静的プロパティの初期化をどのように処理するかを追跡し、そのうえで、補完を診断にするのか、出力を変更するのか、明示的な設計判断とするのかを判断します。回帰ケースで結果を検証します。

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

評価

技術スタック
javascript, typescript
領域
compilers
issue の種類
バグ
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

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

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