microsoft / microsoft/TypeScript
When an index signature is not available, encourage using a more specific type to index the type.
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
Search Terms
index signature, keyof, domain: error messages
Vaguely related:
https://github.com/Microsoft/TypeScript/issues/14951
Suggestion
When there is a type error because of a missing string index signature, add a suggestion of:
"Did you mean to use a more specific type such as keyof Thing instead of string?"
Only show this message:
- if the type used to index is within the same scope
- the object being indexed is not empty
Use Cases
Take the following example:
interface Person {
name: string;
phone: string;
}
declare const person: Person;
const get = (person: Person, key: string) => {
return person[key];
};
get(person, "name");
The error message here is:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Person'.
No index signature with a parameter of type 'string' was found on type 'Person'.
This is technically correct! However, many people read this error message to mean "add an index signature to Person," rather than advising them to use a more specific type than string, like keyof Person. Adding the index signature suppresses the error, making it seem like the correct solution.
Where this doesn't work
There are some cases where this advice would not make sense:
// Did you mean to use a more specific type such as `keyof Number` instead of `string`?
1["a" as string]
Other cases I can think of so far:
- Empty objects, especially from
reduce(suppress for empty objects) - Indexing an object by number (only do this for strings?)
Object.keysandObject.entriesas discussed many, many times (require the indexing type to be in the same scope)
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、文字列インデックス シグネチャがない場合の型チェッカー診断と、関連するテストまたは診断生成のエントリーポイントを見つけます。Person の例と列挙されている例外を使って、どのような場合に提案が表示されるかを確認します。対象のエラーに keyof 形式の提案が含まれ、空のオブジェクト、数値インデックス、またはスコープ外のキーに対する動作を変更しなければ完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100