microsoft / microsoft/TypeScript

Union type resolving to one side of the union when spread operator is used

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

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

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

説明

Bug Report

This issue may be related but they were different enough to warrant a write up here: https://github.com/microsoft/TypeScript/issues/42665

When assigning a union type to a variable, which is immediately instantiated as an object that could possibly be either type at run time, and the spread operator is used to "optionally" apply a property, the type of the variable falls to the type without the extra properties automatically.

🔎 Search Terms

Spread operator, object, union type

🕗 Version & Regression Information

This changed between versions 3.7.5 and 3.8.3.

⏯ Playground Link

Playground link with relevant code

💻 Code
interface Foo {
    bar: string;
}

type Bar = Foo & {
    baz: string;
}

const produceBoolean = () => Math.random() > 0.5;

const obj: Foo | Bar = {
    bar: 'baz',
    ...(produceBoolean() && {
        baz: 'bar'
    })
}

if ('baz' in obj) { // obj is "Foo" here
    console.log(obj); // obj is "never" here
}
🙁 Actual behavior

Instead of remaining a union type until some discrimination was made, it assumed the object was the side of the union without extra properties.

🙂 Expected behavior

It would remain possibly either or any type in the union until discriminated in the code.

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

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

はじめの一歩

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

調査の方向性

リンクされている TypeScript Playground の再現コードから始め、報告されているバージョン 3.7.5 と 3.8.3 の間で動作を比較します。object spread を union に適用する際の型チェックの経路を追跡し、その結果の値が union のままであること、また 'baz' in obj チェックによって正しく絞り込まれることを確認します。

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

評価

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

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

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