microsoft / microsoft/TypeScript
Incomplete typecheck when assigning to a mapped object type with remapped keys
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
🔎 Search Terms
typechecker, mapped object type, remapped keys, ts2322
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about mapped types.
- Tried on
nightlyand every version down to 4.1.5 (first version supporting remapped keys)
- Tried on
⏯ Playground Link
💻 Code
type Shape = { foo: string; bar: number; };
type ShapeMap = { foo: 'foo2'; bar: 'bar2'; };
type MappedShape = { [K in keyof Shape as ShapeMap[K]]: Shape[K] };
function mapValue<K extends keyof Shape>(
key: K,
shape: Shape,
mapped: MappedShape,
map: ShapeMap,
) {
const mappedKey = map[key];
const value = shape[key];
mapped[mappedKey] = value; // <-- Not allowed to assign `value` here
}
🙁 Actual behavior
The error says
Type 'Shape[K]' is not assignable to type 'MappedShape[ShapeMap[K]]'.
Type 'Shape' is missing the following properties from type 'MappedShape': foo2, bar2
The second line is correct, Shape is different from MappedShape since they don't have any property names in common (which is the idea 🙂). That incompatibility is not relevant when it's the value in Shape[K] that should be assignable to MappedShape[ShapeMap[K]].
To an uninitiated eye it looks like the typechecking either ends too early or too late since it compares the wrong types when trying to do the assignment. That's just a guess that might be incorrect so take that with all the salt you want 👍
🙂 Expected behavior
Assigning Shape[K] to MappedShape[ShapeMap[K]] should be allowed since they are the same types when resolved.
Additional information about the issue
If changing the code to always take foo as the key (Playground) it works correctly:
type Shape = { foo: string; bar: number; };
type ShapeMap = { foo: 'foo2'; bar: 'bar2'; };
type MappedShape = { [K in keyof Shape as ShapeMap[K]]: Shape[K] };
function mapValue(
key: 'foo',
shape: Shape,
mapped: MappedShape,
map: ShapeMap,
) {
const mappedKey = map[key];
const value = shape[key];
mapped[mappedKey] = value; // No type error
}
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンク先の TypeScript Playground での動作を再現し、ジェネリックな mapValue の例と、キーを再マッピングしたその mapped type に焦点を当てます。動作する key: 'foo' のバリアントと比較します。ジェネリックな代入が受け入れられ、Shape[K] と MappedShape[ShapeMap[K]] の期待される関係が維持されれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 38/100