microsoft / microsoft/TypeScript

Introduce the opposite of the non-null assertion

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

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

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

説明

Search Terms

non-null assertion opposite

Suggestion

The opposite of the "non-null assertion", used to force the compiler to believe that something may be undefined.

The most obvious syntax would be a "?" postfix operator, similar to how the non-null assertion is a "!" postfix operator. This would be consistent with the use of "?" for optional function params and object properties (which adds "undefined" to the type).

Use Cases

Indexing into arrays and "dictionary" objects with indexes/keys that are expected to potentially not exist.

Arrays and dictionary objects (an object type with the string index defined) are typically defined as having items whose type does NOT include undefined, even though it is technically possible (and valid) to use a non-existent index/key and get an undefined value as a result. In most situations, this avoids unnecessary/tedious non-null assertions, because arrays are often iterated (indexes guaranteed to exist), and dictionary objects are often used only to lookup keys that are guaranteed to exist.

However, in situations where an "untrusted" index/key is used on an array/dictionary, there is no convenient way to alter the type of the expression to indicate that the programmer is aware that the result may be undefined:

Examples

declare const array: Date[];
declare const untrustedIndex: number;

// Type is Date, but it may actually be undefined at runtime.
const item = array[untrustedIndex];

// To get useful "correct" typing, I must explicitly cast, duplicating the type 
// of the item and adding "| undefined" 
const item2 = array[untrustedIndex] as Date | undefined;

// Using the new proposed "possibly undefined assertion"
// Type is Date | undefined
const item3 = array[untrustedIndex]?;

Checklist

My suggestion meets these guidelines:

  • [?] This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

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

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

はじめの一歩

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

調査の方向性

リポジトリのファイル、テスト、エントリーポイントは指定されていません。まず、提案されている postfix 構文と配列および辞書の例を確認し、次に postfix アサーションとインデックスアクセスを処理するコンパイラの領域を特定してください。完了とするには、合意された設計と、説明されている型付けの動作に対して検証された実装が必要です。

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

評価

技術スタック
typescript
領域
compilers
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
20/100

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

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