microsoft / microsoft/TypeScript

Incorporating exhaustiveness analysis into the control flow of if statements.

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

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

Domain: check: Control Flow Possible Improvement
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

🔍 Search Terms

"initialization", "variable", "inference", "assignment", "assigned", "automatic detection"

✅ Viability Checklist
⭐ Suggestion

One's code may implicitely involve that all cases have been processed in an if-else structure. TS does detect it with switch statements, however it does not detect it with if-else clauses.

Consider the following example:

type Dinosaur = "triceratops" | "brachiosaurus"

const myCollectionOfDinosaurs: Dinosaur[] = ["triceratops", "brachiosaurus"]

const randomKey = Math.floor(Math.random() * myCollectionOfDinosaurs.length)
const randomlyChosenDinosaur: Dinosaur = myCollectionOfDinosaurs[randomKey]

let dinosaurGreeting: string

if (randomlyChosenDinosaur === "triceratops") dinosaurGreeting = "Hello triceratops!"
else if (randomlyChosenDinosaur === "brachiosaurus") dinosaurGreeting = "Hello brachiosaurus!"

console.log(dinosaurGreeting)

TS complains on the last line because it says dinosaurGreeting is used before being assigned.

Replacing the if-else clause with a switch statement fixes the problem. However it would be great if TS did support this feature for if-else clauses too.

📃 Motivating Example

I'd use the dinosaurs example above, and assert that this feature would remove unnecessary constraints in the language.

💻 Use Cases
  1. What do you want to use this for?
    Writing some meaningful code with less constraints, shaping it more precisely and remaining safe from type-related problems.
  2. What shortcomings exist with current approaches?
    Most current approaches involve working around the way you intend your code to work. For example I can use !: when typing the variable, or initialize the variable with a default variable, or define it anywhere it is initialized, but all these solutions would imply thinking the code differently, in a way that is less compatible with my need.
    The best approach is using a switch statement instead of an if-else clause, which doesn't impact the logic of the code.
  3. What workarounds are you using in the meantime?
    Replacing the if-else clause with a switch statement.

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

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

はじめの一歩

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

調査の方向性

まず issue の恐竜の例を再現し、その definite-assignment の動作を同等の switch 文と比較します。コンパイラの制御フロー分析と網羅性分析を追跡して、if-else 分岐がどこで処理されるかを特定します。完了の条件は、出力される JavaScript を変更せずに、網羅的な分岐で used-before-assigned エラーが発生しなくなることです。

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

評価

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

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

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