microsoft / microsoft/TypeScript

Deprecate homomorphic mapped type over primitive

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

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

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

説明

🔍 Search Terms

homomorphic mapped primitive

✅ Viability Checklist
⭐ Suggestion

I would like homomorphic mapped types over primitives to emit a warning if the base type is not an object type. An explicit conditional type Foo<T> = T extends object ? { [K in keyof T]: ...} : T can be used to recover the pre-existing behavior. This should be mentioned in the warning message.

Homomorphic mapped type over primitives has surprising behavior that bears mention in the FAQ:

  • This mapped type returns a primitive type, not an object type.
    • Mapped types declared as { [ K in keyof T ]: U } where T is a type parameter are known as homomorphic mapped types, which means that the mapped type is a structure preserving function of T. When type parameter T` is instantiated with a primitive type the mapped type evaluates to the same primitive.

This behavior is surprising since:

  1. It is not referentially transparent; that is, replacing a type parameter with its value does not result in the same type
  2. Although a mapped type may be assignable to the original type, it may specifically not be, e.g. {[k in keyof T]: never} whereas it always is in the case of primitives.
  3. The expression keyof T has surprising behavior on primitive types, differing substantially from object types.
  4. The syntax of a mapped type visually suggests an object-like type, which is incorrect when mapping over null.
📃 Motivating Example
type NullValued<X> = {[k in keyof X]: null};
type Okay = NullValued<{x:1, y:2}>; // {x:null, y:null}
type Oops = NullValued<number>; // oops! This is `number`, which is likely not what you expected
💻 Use Cases
  1. What do you want to use this for?
  2. What shortcomings exist with current approaches?
  • You have to know about homeomorphic mapped types and anticipate this corner case.
  1. What workarounds are you using in the meantime?
  • A type guard type Foo<T extends object> = { [K in keyof T]: ...} guards against the current behavior.
  • A conditional type Foo<T> = T extends object ? { [K in keyof T]: ...} : T makes the current behavior explicit.

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

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

はじめの一歩

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

調査の方向性

動機となる NullValued の例と issue 内の FAQ の記述から始めてください。実装ファイルもテストも指定されていません。homomorphic mapped types が primitive bases に対して要求された警告を生成し、その警告が明示的な conditional workaround を説明し、さらにその意外な挙動が FAQ に記録されていれば完了です。

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

評価

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

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

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