microsoft / microsoft/TypeScript
Infer a tuple type instead of array type when possible
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
Suggestion
I'd prefer typescript to be more aggressive about inferring tuple types, instead of always defaulting to Array.
This is related to https://github.com/microsoft/TypeScript/issues/6574. I'd like to open up a discussion about this again since that thread is locked, and conversation stopped after a workaround was provided without completely addressing the general issue.
🔍 Search Terms
Typescript, tuple, tuples, map, inference
✅ Viability 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, new syntax sugar for JS, etc.)
- [*] This feature would agree with the rest of TypeScript's Design Goals.
Existing typescript code could start emitting type errors from this change, so it would make sense to provide this as an option in tsconfig.
⭐ Suggestion
Typescript should infer a type to be a tuple instead of an array when it's possible.
📃 Motivating Example
The specific example I have in mind is for Array.prototype.map(), but there are probably more.
const tuple: [number, number, number] = [1, 2, 3];
const result = tuple.map(value => value + 1);
Here, typescript infers the type of result to be number[] rather than [number, number, number]. This could result in some wonkiness when trying to access values inside the tuple:
const [a, b, c, d] = result; // Typescript doesn't detect an error since result is an Array type.
const e = result[10]; // Typescript doesn't detect an error since result is an Array type.
Both of these errors can be caught if Typescript instead inferred result to be the tuple type [number, number, number].
💻 Use Cases
The above example is a use case. I want typescript to tell me when I make errors in my code.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、Array.prototype.map() に対する TypeScript の推論動作と、issue #6574 でのこれまでの議論を確認します。提案されている tsconfig オプションを含め、マップされたタプルがタプル型を保持すべき条件を定義し、無効なタプルアクセスが拒否される一方で、有効なマップ結果は引き続き機能することを示すテストを追加します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 25/100