microsoft / microsoft/TypeScript

Narrowing from `typeof x !== 'object'` incorrectly excludes functions.

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

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

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

説明

Bug Report

🔎 Search Terms

typeof object function narrow, type narrowing

🕗 Version & Regression Information

Present in all recent versions from at least 3.3.3333 through the current nightly 4.4.0-dev.20210701

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "typeof" and "narrow"
⏯ Playground Link

Playground link

💻 Code
let x!: string|object; // |Function;
if (1 < 2) x = () => 1;

if (typeof x !== 'object') {
  useString(x); // should fail, but doesn't
}

declare function useString(s: string): void;
🙁 Actual behavior

The type narrowing for typeof x !== 'object' pruned the entire |object branch from x's type union, but typeof can return either "object" or "function" for values of type object, so this is overzealous. This causes x inside the conditional to be incorrectly narrowed to just string when we can clearly see from the earlier line that it's been assigned a function, which is incorrectly passed to useString with no complaint.

🙂 Expected behavior

Excluding "object" from typeof x should not remove |object from its type, in the same way that it doesn't narrow unknown any further. This would cause the appropriate type error from passing a function to useString.

Note that if an explicit |Function branch is added to to x's type union then the narrowing proceeds as expected.

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

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

はじめの一歩

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

調査の方向性

リンク先の TypeScript Playground と提供された narrowing の例から始め、typeof x !== "object" に対する型の narrowing ロジックを追跡してください。x に代入された関数が narrowing によって除外されず、xuseString に渡すと期待される型エラーが発生すれば修正は完了です。記載されたバージョンで動作を確認してください。

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

評価

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

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

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