microsoft / microsoft/TypeScript

Type narrowing is lost when using logical OR assignment

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

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

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

説明

Bug Report

🔎 Search Terms

logical assignment, narrowing

🕗 Version & Regression Information

The behaviour is consistent across all versions since the introduction of logical assignment operators in TypeScript 4.0.
Checked range from 4.0.5 to Nightly, no changes in behaviour observed.

⏯ Playground Link

Playground link with relevant code

💻 Code
type F = () => number;

type R = {
  [ x: string ]: R | F | undefined
}

const isFunc = <T extends (...args: any[]) => any>(maybe:unknown) : maybe is T => typeof maybe === "function";

const check = (i: R) => {

  let tmp:R = i;

  let curr = tmp["something"]; // R | F | undefined, expected

  if( isFunc<F>(curr) ) return;

  curr // R | undefined, expected

  tmp = curr || (curr = {}); //ok, expected

  tmp = curr ||= {}; // Type 'R | F' is not assignable to type 'R'.
};
🙁 Actual behavior

Error 2322 on the second tmp assignment because R | F is not narrowed to R as with the curr || (curr = {})

🙂 Expected behavior

No error since both assignments to tmp are functionally equivalent
(I might be missing something obvious about how logical assignment is intended to work from the type system standpoint)

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

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

はじめの一歩

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

調査の方向性

リンクされた TypeScript Playground から始め、指定されたバージョン全体で curr || (curr = {})curr ||= {} の違いを再現してください。論理代入に対する制御フローの絞り込みの挙動を追跡してください。完了の条件は、同等のコードが報告された TS2322 エラーなしで型チェックを通ることです。

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

評価

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

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

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