microsoft / microsoft/TypeScript
Cannot assign to ... because it is a read-only property when using type guard in ctor
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
A common pattern is declaring narrower types for members in derived classes. However, when combined with type guards, assignement to readonly members fails with an unexpected "Cannot assign to ... because it is a read-only property" error.
TypeScript Version: 3.7.2
Search Terms:
class member read-only property type narrowing covariant type guard
Code
class Foo {
public readonly x: string | number;
constructor() {
if (isBar(this))
// error TS2540: Cannot assign to 'x' because it is a read-only property.
this.x = 'string';
else
// no error here
this.x = 123;
}
}
class Bar extends Foo {
// Declare narrower type for member in derived class
public readonly x: string;
}
function isBar(foo: Foo): foo is Bar {
return foo instanceof Bar;
}
Expected behavior:
Assignment to this.x should be allowed with or without type guard in the constructor
Actual behavior:
error TS2540: Cannot assign to 'x' because it is a read-only property.
Playground Link:
Related Issues:
It is as if the type guard creates an invisible alias (cf https://github.com/microsoft/TypeScript/issues/14241), and asignment inside the type guard fails.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、リンク先の Playground で TypeScript 3.7.2 の例を再現し、guarded assignment と unguarded assignment を比較します。次に、コンパイラーの型ガードと readonly プロパティのチェックを追跡し、その後、例の回帰テストを追加します。両方のコンストラクター代入が TS2540 を発生させずに受け入れられれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100