Predicate `value is object` doesn't work in Array.prototype.filter()

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

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

評価

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

調査の方向性

リンクされた TypeScript Playground の再現コードから始め、isNumber と isObject で Array.prototype.filter() が型述語をどのように適用するかを比較してください。filter の述語に対する型チェックの経路を追跡し、混在配列をフィルタリングすると { a: number }[] になることを示すカバレッジを追加して、関連するコンパイラテストを実行してください。

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

説明

Awaiting More Feedback Suggestion

Bug Report

🔎 Search Terms

type narrowing, type predicate, value is object, filter(), lodash.isObject

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type guards.
⏯ Playground Link

Playground link with relevant code

💻 Code
// isNumber and isObject are modeled after the functions by the same names in lodash.

function isNumber(value?: any): value is number {
  return typeof value === "number";
}

function isObject(value?: any): value is object {
  return typeof value === "object";
}

// Each element could be an object or a number, so we can't treat it as either.
const variousThings = [{ a: 1 }, 1, "abc"];
variousThings[0] + 1;
variousThings[0].a;

// Filtering for only numbers yields values we can add, but not get properties of.
const allNumbers = variousThings.filter(isNumber);
allNumbers[0] + 1;
allNumbers[0].a;

// But filtering for only object yields fails to remove number from the union type.
const allObjects = variousThings.filter(isObject);
allObjects[0] + 1;
allObjects[0].a;

// Yet isObject is able to narrow a single element in a simple conditional.
const value = variousThings[0];
if (isObject(value)) {
    value.a
}
🙁 Actual behavior

allObjects was typed as (string | number | { a: number })[], so both lines below const allObjects fail.

🙂 Expected behavior

allObjects should be typed as { a: number }[], so allObjects[0].a should pass the type checker. Notably, as seen above, isObject does manage to narrow the type of a single value with the union type to the only member of the union that's an object, it just can't narrow all of the elements using .filter() the way isNumber is able to.

I can't conceive of why they behave differently, but I also don't know the internals well. I think this difference is undesired, but I might be missing something deeper.

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

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

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

はじめの一歩

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

microsoft/TypeScript のほかの issue

microsoft/TypeScript の issue をすべて見る

似ている issue

Go の issue をもっと見る

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

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