microsoft / microsoft/TypeScript

Type narrowing not working as expected in else

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

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

In Discussion Suggestion
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

For the following code with strictNullChecks enabled:

interface Base {
    a: {} | null;
    b: {} | null;
}

function test(base: Base): void {
    if (!base.a && !base.b) {
        const result: null = null;
    } else if (!base.a && base.b) {
        const result: {} = base.b;
    } else if (base.a && !base.b) {
        const result: {} = base.a;
    } else {
        const result: {} = base.b;
    }
}

I'm seeing this error on the last result:

Type '{} | null' is not assignable to type '{}'.
  Type 'null' is not assignable to type '{}'.

I expect it to work as the else implies:

   !(!base.a && !base.b) && !(!base.a && base.b) && !(base.a && !base.b) 
 = (base.a || base.b) && (base.a || !base.b) && (!base.a || base.b)
 = (base.a || base.b) && (base.a) && (base.b)
      note: !base.b and !base.a are canceled out as the expression cannot be true if one
            of them is false
 = base.a && base.b

TS play link

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

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

はじめの一歩

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

調査の方向性

Issue にリンクされている TypeScript Playground の再現コードから始め、strictNullChecks 下で final else branch に推論される型を確認してください。連鎖した if/else 条件に対するコンパイラーの control-flow narrowing を追跡します。報告された代入が、他の narrowing の挙動を弱めることなく受け入れられれば完了です。

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

評価

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

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

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