microsoft / microsoft/TypeScript

Discriminated union with 11+ items does not handle nullability same as union with <10 items

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

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

Bug Domain: check: Big Unions Help Wanted
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
2日 4時間
マージ済み PR(30日)
132

説明

🔎 Search Terms

10 11 union undefined type
Nullability narrowing is inconsistent between type discriminated unions of <=10 items and >10 items

🕗 Version & Regression Information
  • This changed between versions 4.2.3 and 4.3.5 (before it would complain about undefined in both cases)
⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.9.2#code/PTAEFUDsEsHtNAd2gFwBagIyYNSlQKYC2AzqACawFmSwqhoCGk5ANgaJAK6uuMBG0VqgCeoEoyIdGZLjHhJUGADyYADPhTESAKHIEAxnwBOHdvUYBmAFygA3qBQiADgVsAiTO9ABfUAB97Rxc3UHcAJm8-QLl9ADNoSAJyAG4daDiACisAQgA6J1dQAF5SsK8ASjsdUFrQEFAAcitG-DJnWBISaH5WMUbYggSk8ka8zMwADjUAFkmKmrqDeBJYdjzWWABzbMsCkIq0nx09QxMzAgt1WwdC0M8ogKC7j0jfJ9uQj0tHwM-XDwzX7PL5hACswP+9wAbJDggCwgB2OEvMKTFGg9wATgxCM8amBg2GyTSGWy6nydxKZQeVUWtQaADlYKACMZjLBjKBMvxLloubymAA3ODGAD8CzqoGWkFW602O0Y6n2rkOOh8QA

💻 Code
// Union with 11+ items does not handle nullability same as union with <10 items
declare let a3: { type: "1" } | { type: "2" } | undefined;
if(a3!.type === "1"){
    // 'a3' is possibly 'undefined'.(18048)
    console.log(a3.type);
}

declare let a10: { type: "1" } | { type: "2" } | { type: "3" } | { type: "4" } | { type: "5" } | { type: "6" } | { type: "7" } | { type: "8" } | { type: "9" } | { type: "10" } | undefined;
if(a10!.type === "1"){
    // No error (better behavior?)
    console.log(a10.type);
}
🙁 Actual behavior

Complains about undefined for unions with >10 members, but not for unions <11

🙂 Expected behavior

It seems like it should not error in either case - the code inside the if can only execute if the a3 variable is not undefined

Additional information about the issue

Relevant function in checker.ts: getKeyPropertyName(). That is where the 10 magic value comes from.

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

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

はじめの一歩

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

調査の方向性

提供されているPlaygroundの再現から始め、checker.ts、特に10項目のしきい値が特定されているgetKeyPropertyName()を調べてください。2つのunionサイズについてnullabilityのnarrowingを比較し、issueに記載されている期待される動作を考慮してください:どちらの例も、ガードされたブロック内でundefinedを報告すべきではありません。

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

評価

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

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

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