microsoft / microsoft/TypeScript

Double initializing a `readonly` field should not be allowed

オープン
#61,716 コメント 4 件 リアクション 3 件 担当者 0 名 GitHub で見る

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

Awaiting More Feedback Suggestion
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
2日 4時間
マージ済み PR(30日)
132

説明

🔎 Search Terms

readonly double twice initializer

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about initializers?
⏯ Playground Link

https://www.typescriptlang.org/play/?#code/MYGwhgzhAEBiD29oG8BQ0PQE4FMwBN4A7EAT2gCMwsAuaCAFywEsiBzaAXmgHJXmGzMCGYAvHFmgBGHgG5U6TMGKMsAV2AN4WABQBKFIsyYGAC2YQAdFUnc+RAUJHjJAJjlHoAX1Q-Uyogh4EBxLEHg2HSIcAHc4RH1raj1ZIA

💻 Code
class Foo {
    readonly bar: string = 'initializer 1';

    constructor() {
        this.bar = 'initializer 2';
    }
}

console.log(new Foo().bar);
🙁 Actual behavior

This compiles successfully despite overwriting a readonly field. This breaks expectations around readonly. If Foo happens to be a very large class and I only look at readonly bar: string = 'initializer 1'; in isolation, I would expect any other line which reads bar to see initializer 1. However this is not a safe assumption because I need to check in the constructor to ensure it doesn't overwrite my readonly field.

🙂 Expected behavior

I expected a compiler error. TS should only allow initializing readonly fields in a constructor, not overwriting a field which has already been initialized.

Additional information about the issue

I get that we need readonly fields to be assignable in the constructor, but it feels like a bug to me that this is allowed when the field has already been initialized prior to the constructor. readonly should require a field initializer xor a constructor initializer. Having both is invalid IMHO.

You can make the same argument that double initializing in the constructor should be invalid too:

class Foo {
  readonly bar: string;

  constructor() {
    this.bar = 'initializer 1';
    this.bar = 'initializer 2'; // Should maybe error? Doesn't today.
  }
}

But I understand that control flow analysis gets a lot more complicated in the constructor WRT readonly and might be considered a different feature with different priority.

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

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

はじめの一歩

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

調査の方向性

まず、リンクされた TypeScript Playground の例を実行し、フィールド初期化子のケースとコンストラクター内だけで二重に代入するケースを比較します。最初の例で、すでに初期化されている readonly フィールドへの代入に対してコンパイラーエラーが発生し、要求された動作が回帰テストでカバーされれば、変更は完了です。

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

評価

技術スタック
typescript
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
35/100

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

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