microsoft / microsoft/TypeScript

Incorrect union type inference for conjunction with strictNullChecks disabled

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

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

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

説明

TypeScript Version: 3.4.5

Search Terms: union type inference conjunction strictNullChecks

Code

function fn(x: number) {
  return x && 'a'
}

Expected behavior:
Return type of fn should be 0 | 'a'

Actual behavior:
Return type of fn is '' | 'a' if strictNullChecks is disabled

This is causing me an issue with this specific bit of code, where I'm checking window so my code runs both on the browser and on the client:

function fn(x: number): OrientationType | undefined {
  return window && (window.outerWidth > window.outerHeight ? 'landscape-primary' : 'portrait-primary')
}

I can replace the conjunction with a conditional expression, and I know that if strictNullChecks is disabled I should have a fallback for the return value but I'm posting here for the sake of trying to understand if this is working as intended. It also feels weird that my example compiles with strictNullChecks enabled but doesn't compile when it's disabled.

Playground Link: https://www.typescriptlang.org/play/#src=function%20fn(x%3A%20number)%3A%20OrientationType%20%7C%20undefined%20%7B%0D%0A%20%20return%20window%20%26%26%20(window.outerWidth%20%3E%20window.outerHeight%20%3F%20'landscape-primary'%20%3A%20'portrait-primary')%0D%0A%7D

Related Issues:

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

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

はじめの一歩

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

調査の方向性

まず、リンクされている TypeScript Playground の例を strictNullChecks を無効にした場合と有効にした場合の両方で再現します。型チェッカーが fn(x: number) の論理積式をどのように推論するかを追跡します。無効にした設定で期待される戻り値の型 0 | 'a' が生成され、有効にした設定や window の例を壊さなければ完了です。

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

評価

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

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

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