microsoft / microsoft/TypeScript
Infer const-ness of local let bindings that aren't assigned to
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.3k
- 平均マージ
- 2日 4時間
- マージ済み PR(30日)
- 132
説明
Search Terms
let const infer assignment
Suggestion
In some cases, type narrowing for const bindings is more effective than for let bindings. Specifically, using such bindings from a function that closes over them will keep the narrowed type, which doesn't happen for let binding, presumably on the assumption that those might be mutated at any time.
This suggests to treat local let bindings that are never assigned to (which can be determined by a rather straightforward static check on the syntax tree) like const bindings for this purpose.
(Interestingly, something like this seems to already exist for function parameters.)
Use Cases
Though some people have adopted a coding style where locals are declared with const unless assigned to, there's also a good argument to be made that that is not a very good use of brain cycles and just using let for all locals is fine. This proposal would improve type inference for people using the let style.
Examples
function foo() {
let v: number[] | null = Math.random() < 0.5 ? [1] : null
if (Array.isArray(v)) setTimeout(() => console.log(v.length), 100)
}
The compiler complains that v is possibly null. If the binding is changed to const the problem goes away. If v is made a function parameter it also doesn't occur. (But comes back when a v = null statement is added, suggesting a check like the one suggested here is being done in that case.)
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
提供された foo の例から始め、提案されている local-let の挙動を、const バインディングおよび関数パラメーターに対する既存の挙動と比較します。ローカルな let バインディングに代入がない場合に、クロージャ callback 内で絞り込まれた型を維持することを補完と定義し、変更可能な場合は既存の挙動を維持します。両方のケースのカバレッジを追加します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100