microsoft / microsoft/TypeScript

Type narrowing down on a union type with null results in incorrect type when applying `typeof`

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

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

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

説明

Bug Report

🔎 Search Terms

type narrowing down, typeof

🕗 Version & Regression Information

I've tested all versions until 4.4.0 (Nightly)

⏯ Playground Link

https://www.typescriptlang.org/play?ts=4.4.0-dev.20210706#code/C4TwDgpgBAwg9gO2AQwJYIgJygXigbygGNEV0sAuA0SKgIgDM446BfKAH2vAnoCNkmNpygIArgBsJUVgFgAUAoZiERYKkRRgEAM7AAFOjBjgVeEjQZMASgIKoDqKgZRDCY8AB0JC+UwB+TxpoHFCoAHImOHDbfHtHBIB6RKgAdzhMAGsdeISHZCIiCDBgHQAxZjcPb1JLLGsAbly8gqKS8sr8YPootmtmpJSAEThdUThgNIzsgcdW4tKKuCqTGt8rKGQdLR44FyNVnzIrfvk8ucKFjuWunh7mYS2dyD2nd0Pav1OEuXlfpRUag0CE2l3aSxWpm4tCgjAerFirCAA

💻 Code
type Container = { container: {type: "foo"} | {type: "bar"} | null }

function test(input: Container) {
    if (input.container?.type === 'foo') {
        // works
        acceptsFoo(input.container);
        acceptsFoo({type: "foo"})
        // Does not works
        acceptsFoo(input.container as typeof input.container)
        acceptsFoo({type: "foo"} as typeof input.container)
		/**
Error:
 Argument of type '{ type: "foo"; } | null' is not assignable to parameter of type '{ type: "foo"; }'.
  Type 'null' is not assignable to type '{ type: "foo"; }'.(2345) \
**/
    }
}

function acceptsFoo(input: {type: "foo"}) {}
🙁 Actual behavior

input.container and input.container as typeof input.container are not equivalent.

🙂 Expected behavior

input.container and input.container as typeof input.container should be equivalent.

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

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

はじめの一歩

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

調査の方向性

提供された Container と test function を使用して、リンク先の TypeScript Playground で報告された narrowing の挙動を再現します。まず、optional property の narrowing と typeof assertions を type-checker がどのように処理するかを追跡します。input.container と input.container as typeof input.container が nullability error なしに同等に扱われれば完了です。

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

評価

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

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

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