microsoft / microsoft/TypeScript

Optional chaining should always include `undefined` in its resolved type

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

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

In Discussion Suggestion
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

TypeScript Version: 3.7.5

Search Terms: optional chaining return type

Code

I have a formatting function, where the input should always be a string, but in certain cases, from the backend, it's undefined for some reason. So to make sure the front-end at least doesn't crash when that happens, I added optional chaining, which fixed the issue.

But the types are kind of off now, and I didn't realize until now because Typescript didn't complain about anything.

export const formatAccountNumber = (account: string): string =>
  account?.replace(/^(\d{4})(\d{2})(\d{5})/, '$1 $2 $3');

Expected behavior: Should get an error/warning about something here. Preferably, I guess optional chaining should always expand the type to include undefined to whatever it is added to? Then, in this example, Typescript could say that the return type is string, but I'm trying to return string | undefined? Either that, or maybe it shouldn't be possible to use optional chaining on a value that does not include either the type undefined and/or null?

Actual behavior: No warnings or errors.

Related Issues: no

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

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

はじめの一歩

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

調査の方向性

まず、optional chaining と明示的な string 戻り値型を使用する TypeScript 3.7.5 の例を再現します。意図した修正が、解決された型に undefined を含めることなのか、null 非許容値に対する optional chaining を拒否することなのかを判断します。選択した動作が一貫して適用され、コンパイラテストでカバーされれば完了です。

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

評価

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

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

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