microsoft / microsoft/TypeScript

Bug: null can be excluded by !== null in flow before typeof === 'object', but not excluded by predicate function.

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

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

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

説明

🔎 Search Terms

"null", "control flow", "narrowing", "narrow", "exclusion", "object", "typeof"

🕗 Version & Regression Information

Potentially, we could expect the behaviors of if (a === null) and if ((v => v !== null)(a)) (inferred as predicate since TS 5.5) should be the same, but it's actually not in specific cases.

If it's combined with typeof a === 'object' check in the same flow, first one is correctly omits the null possibility, while second one doesn't.

image

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.6.2#code/MYewdgzgLgBAlhAcgVwDapgXhgCgG4BcMyYA1mCAO5gCUWAfDHlptmGqgNwBQA9LzEEwAegH5uoSLABmWXAEMiJclVoMYAb25D4snAhToc8mnQBOAUyjIzYHjrh6oATwAOFkLPkwAhKxgA5CAARgBWFsBQAeZWNnbaQvL2-CLiAL483BLg0DAA5nLGSmQU1HSYjFoOet6sbBwx1rb2Qo64Lu6eMN5+2EFhEVGNcS2CSdopYtwZQA

💻 Code
const isNull = (v: unknown) => v === null;
//    ^?
const f = (a: unknown) => {
    if (isNull(a)) return;
    if (typeof a !== 'object') return;
    a;
 // ^?
};


const g = (a: unknown) => {
    if (a === null) return;
    if (typeof a !== 'object') return;
    a;
 // ^?
};
🙁 Actual behavior

Last a in f is inferred as object | null.

🙂 Expected behavior

Last a in f would be inferred as object.

Additional information about the issue

Here is important to check typeof === 'object' after the check for null, because type narrowing step is formally, unknownobject | nullobject. === null alone cannot narrow anything on unknown.

If you swap the if-statements in above, you can see both is inferred as object.

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

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

はじめの一歩

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

調査の方向性

TypeScript Playground のリンクと f および g の最小再現から始め、typeof チェック後の推論された型を比較します。違いの原因となっている control-flow narrowing と推論された predicate の動作を追跡します。完了条件は、predicate のケースで a が null なしの object に絞り込まれ、報告された例に対するリグレッションカバレッジが追加されていることです。

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

評価

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

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

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