microsoft / microsoft/TypeScript

Can't constrain a generic parameter to have string keys?

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

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

Bug Domain: Index Types
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

Bug Report

Search Terms: Type 'X' cannot be used to index type 'Y', constrain generic parameter to have string keys

  • This is the behavior in every version I tried
Code

Playground link

This type is meant to map another type's values to arrays of {message: V} but also allow {message:unknown} for other string keys.

type Example<M> =
  { [K in keyof M]?: {message: M[K]}[] } &
  { [key in string]: {message: unknown}[] };

For example, the intent is that Example<{ foo: string }> should become

{
  foo: {message: string}[];
  [key: string]: {message: unknown}[];
}

And this works: we know that "foo" and other strings are valid keys.

const obj: Example<{foo: string}> = {};
obj["foo"] = [{message: "hi"}];
obj["bar"] = [{message: "x"}];

But trying to use Example with a generic parameter gives errors. Even if we don't know M["foo"], we should know that keyof M is string.

// attempt to constrain M's keys to be strings
function test<M extends {[key in string]: unknown}>() {
  const obj: Example<M> = {};
  obj["foo"] = [];  // error: Type '"foo"' cannot be used to index type 'Example<M>'.
  obj["bar"] = [];  // error: Type '"foo"' cannot be used to index type 'Example<M>'.
}
// should fail, but doesn't -- we've tried to constrain M to have string keys
test<{ 4: string }>();
🙁 Actual behavior

Example<M> cannot be indexed using string when M is a generic parameter.

🙂 Expected behavior

It should always be possible to index with string, since the definition of Example includes { [key in string]: ... }.

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

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

はじめの一歩

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

調査の方向性

リンクされた TypeScript Playground の再現コードから始め、具体的な Example<{ foo: string }> のケースと、ジェネリックな test<M extends { [key in string]: unknown }>() のケースを比較してください。ジェネリックな indexed access とキー制約の挙動を調査し、ジェネリックな Example で string によるインデックスアクセスが機能し、数値キーによるインスタンス化が拒否されれば完了です。

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

評価

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

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

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