microsoft / microsoft/TypeScript

Checking union type where key is enum tricks compiler

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

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

Bug Domain: check: Control Flow
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
2日 4時間
マージ済み PR(30日)
132

説明

TypeScript Version: 3.9.2

Search Terms:
enum refinement
checking interface enum

Code

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
enum Fish {
    blue= 1,
    red= 2
}

enum Crab {
    purple= 2
}

interface IFish {
    type: Fish,
    name: string,
}

interface ICrab {
    type: Crab,
    shell: string
}

const crab = {type: Crab.purple, shell: "hard"}

function determineAnimal(animal: ICrab | IFish) {
    if (animal.type === Fish.red) {
        console.log("fish")
        console.log(animal.name)
    } else if (animal.type === Crab.purple) {
        console.log("crab")
        console.log(animal.shell)
    } else {
        console.log("fell through")
    }
}

determineAnimal(crab)

Expected behavior: The program does not typecheck because checking against the enum does not prove the animal is an IFish

Actual behavior: The program typechecks and incorrectly determines the type of the crab, logging undefined.

Playground Link: link

Related Issues:

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

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

はじめの一歩

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

調査の方向性

tsc のコマンドラインエントリーポイントを使って自己完結した enum と union の例を再現し、誤った narrowing の挙動を確認します。コンパイラーが enum と union メンバーの比較をどのように検査するかを追跡し、Crab ケースから IFish プロパティにアクセスできないことと、報告された期待される挙動が適用されることを示すカバレッジを追加します。

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

評価

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

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

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