microsoft / microsoft/TypeScript

Inconsistent key type inference when spreading objects with const assertion into plain objects

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

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

Domain: check: Type Inference Help Wanted Possible Improvement
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

🔎 Search Terms

const assertion, type inference, as const, object keys, type conversion, keyof typeof, satisfies, spread, readonly object

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about keyof, as const, infererence etc.
⏯ Playground Link

Playground

💻 Code
const namesById = {
  1: "John Doe",
  2: "Jane Smith",
  3: "Alex Johnson",
  4: "Maria Garcia",
} as const satisfies Record<number, string>;

type Ids = keyof typeof namesById;
//   ^? type Ids = 1 | 2 | 3 | 4

const namesByIdCopy = {
  ...namesById,
} satisfies Record<number, string>;

type IdsCopy = keyof typeof namesByIdCopy;
//   ^? type IdsCopy = "1" | "2" | "3" | "4"

🙁 Actual behavior

IdsCopy has converted all of the keys to string literal union instead of a number literal union when using keyof typeof, even despite the fact that we've used satisfies Record<number, string> on the namesByIdCopy object.

🙂 Expected behavior
type IdsCopy = keyof typeof namesByIdCopy;
//   ^? type IdsCopy = "1" | "2" | "3" | "4"

should instead be typed as:

type IdsCopy = keyof typeof namesByIdCopy;
//   ^? type IdsCopy = 1 | 2 | 3 | 4
Additional information about the issue

The type inference seems to work as expected (i.e. numeric literal union) if as const is used on both the original object and the copy object, or if as const isn't used on the original object. It's only when spreading the object with anas const and inferring the keys using keyof typeof that they get inferred incorrectly.

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

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

はじめの一歩

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

調査の方向性

リンクされている TypeScript Playground から始め、提供された再現例で推論される Ids 型と IdsCopy 型を比較します。as const オブジェクトのスプレッドが keyof typeof と satisfies Record<number, string> 制約にどのような影響を与えるかを追跡します。期待される動作に示されている数値リテラルのユニオンがコピーされたオブジェクトのキーに保持されれば完了です。

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

評価

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

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

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