microsoft / microsoft/TypeScript

Double initializing a `readonly` field should not be allowed

未关闭
#61,716 4 条评论 3 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Awaiting More Feedback Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
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

```ts
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:

```typescript
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. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先运行链接的 TypeScript Playground 示例,并比较字段初始化器的情况与仅在构造函数中进行双重赋值的情况。当第一个示例在向已初始化的 readonly 字段赋值时产生编译器错误,并且所要求的行为由回归测试覆盖时,此更改即完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
typescript
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。