microsoft / microsoft/TypeScript
Proposal: better type narrowing in overloaded functions through overload set pruning
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.3k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
TypeScript Version: 2.7.2
Search Terms: type inference, type narrowing, overloads
Code
function bar(selector: "A", val: number): number;
function bar(selector: "B", val: string): string;
function bar(selector: "A" | "B", val: number | string): number | string
{
if (selector === "A")
{
const the_selector = selector; // "A"
const the_val = val; // number | string but should be just number
return "foo"; // should give error: when selector is "A" should return a number
}
else
{
const the_selector = selector; // "B"
const the_val = val; // number | string but should be just string
return 42; // should give error: when selector is "B" should return a string
}
}
Issue
The snippet above shows a limitation of the current type inference implementation in TypeScript.
As can be clearly seen from the overloaded declarations, when selector === "A" we have val: number and we must return a number, while when selector === "B" we have val: string and we must return a string. But the type-checker, although able to understand that the_selector can only be "A" in the if block and only "B" in the else block, still types the_val as number | string in both blocks and allows us to return a string when selector === "A" and a number when selector === "B".
Possible Solution
In the implementation of an overloaded function, when the type-checker decides to narrow the type of a parameter (as often happens in if-else blocks), it should also remove the overloads that don't match the narrowed parameter type from the overload set, and use the pruned overload set to narrow the types of the other parameters.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンクされた TypeScript Playground でオーバーロードされた関数の例を再現することから始め、絞り込まれたパラメーターに対する type-checker の動作を調べます。各分岐で推論された型と受け入れられる return 文を比較します。関連するパラメーターと戻り値の型が残った overload に対してチェックされるよう、overload の集合が一貫して絞り込まれれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100