Incorrect narrowing of Union type after discrimination when one type is assignable to the other (even when explicit type annotation is present)

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

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

評価

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

調査の方向性

リンクされている TypeScript Playground の再現コードから始め、注釈付きの obj1 のケースと動作する obj2 のケースを比較します。assignable な union メンバーに対する type guard の narrowing 動作を追跡し、そのうえで WithoutFlags に追加のプロパティを要求せずに、期待される両方の動作が成立することを確認します。

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

説明

Bug Domain: check: Control Flow Help Wanted
🔎 Search Terms

"discriminating assignable union", "narrowing unions", "unions simplifying with type guards", "type narrowing with union types", "type discrimination with assignable types", "union type annotation issue", "type guard narrowing problem"

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Type Guards and Structural Typing
Playground Link
💻 Code
type ObjWithoutFlags = {withoutFlags: WithoutFlags};
type ObjWithFlags = {withFlags: WithFlags}

export interface WithoutFlags {
  id: string
  // if you add any additional field here, it suddenly works correctly:
  // extraField: any
}

export interface WithFlags {
  id: string
  flags: Array<string>
}

declare const props: ObjWithoutFlags | ObjWithFlags

// broken case:
// regardless of whether I explicitly define that type of `obj1` is a union of `WithFlags | WithoutFlags`,
// TS assumes that `obj1` is always `WithoutFlags` when used in conjunction with type discrimination like so:
const obj1: WithFlags | WithoutFlags = 'withoutFlags' in props ? props.withoutFlags : props.withFlags;

// obj1 is narrowed to `WithoutFlags`, despite having an explicit type annotation

if ('flags' in obj1) {
  // obj is incorrectly narrowed to `WithoutFlags & Record<"flags", unknown>`
  // error, because event.flags is 'unknown', even though it should be an `Array<string>`
  obj1.flags[0]
}

// working case, almost identical:
// there's no discrimination at play, and it works as intended:
declare const obj2: WithFlags | WithoutFlags;

if ('flags' in obj2) {
  // obj is narrowed to `ObjWithFlags`
  // no error, because event.flags is correctly `Array<string>`
  obj2.flags[0]
}
🙁 Actual behavior

When accessing properties of a discriminated union type, where one resulting type is assignable to the other, TypeScript incorrectly narrows down the resulting type to the intersection of its types, rather than their union. Simply adding an additional property to the type that's assignable to the other makes TypeScript switch behavior, and use a union type instead.

This occurs even when an explicit type annotation is present on the variable. This behavior is observed not just with conditional ternary expressions but with any type guards.
This leads to an erroneous assumption, for instance, that the object type only contains the fields of the simpler type - in the example case, it is always of type WithoutFlags, even if the explicit annotation indicates a union of WithFlags | WithoutFlags.

const obj1: {flags: string[], id: string} | {id: string} = 'withoutFlags' in props ? props.withoutFlags : props.withFlags;

if ('flags' in obj1) {
  // Error: obj1.flags is considered 'unknown' instead of `Array<string>`
  obj1.flags[0]
}
🙂 Expected behavior
  1. TypeScript should always create unions of possible types, unless both types are mutually assignable. Currently it's enough if one of the types is assignable to the other.

  2. When a variable is annotated with an explicit type, TypeScript should disregard any magic inference behavior that happens in its initializer

Additional information about the issue

We've stumbled upon this issue accidentally in the real world, because code that used to work, suddenly was erroring. A refactor of GraphQL Fragments that unified two distinct property types into one, suddenly made TypeScript behave as if only one of those distinct types was correct, and all the excess properties were missing, even after applying a type guard to test for which one of the types is being used.

主要言語
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 を短くまとめたダイジェスト。