microsoft / microsoft/TypeScript
Can't constrain a generic parameter to have string keys?
まだ誰も着手していません。
- 主要言語
- 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
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]: ... }.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- 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