microsoft / microsoft/TypeScript

Overload resolution selects most narrow overload when `any` is involved

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

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

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

説明

TypeScript Version: 4.0.0-dev.20200730

Search Terms: any overload

Code

declare class Endpoint {}

declare function getEndpoint(index: number): Endpoint | undefined;
declare function getEndpoint(index: 0): Endpoint;

declare const i1: number | undefined;
const e1 = getEndpoint(i1 ?? 0); // Endpoint | undefined, as expected

declare const i2: any;
const e2 = getEndpoint(i2); // Endpoint, expected Endpoint | undefined

Expected behavior:
The type of e2 should include undefined, since we cannot know that the most narrow overload always matches.

Actual behavior:
It does not.

I understand that it is not always possible to select a sound overload, especially when the possible argument types are not strictly subsets of each other. However choosing the most narrow overload does not seem correct.
Take this extension of the repro for example:

declare class Endpoint {}

declare function getEndpoint(index: number): Endpoint | undefined;
declare function getEndpoint(index: 1 | 2): "FOOBAR";
declare function getEndpoint(index: 0): Endpoint;

declare const i3: any;
const e3 = getEndpoint(i3);

Here, e3 is inferred as Endpoint. When I change the argument in the 2nd overload to 1 instead of 1 | 2, e3 suddenly has type "FOOBAR". I would argue that it is not possible to narrow to any overload here, since i3 could be any number (or even any other type).
Therefore I believe that the most sound result would be the union of all return types, that is Endpoint | undefined | "FOOBAR".

Playground Link: Playground Link

Related Issues: none found that seems to match this one

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

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

はじめの一歩

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

調査の方向性

TypeScript playground での再現から始め、引数の型が any である呼び出しのオーバーロード解決を追跡してください。e2 と e3 の推論された型を、期待される戻り値型のユニオンと比較してください。報告されたケースで最も狭いオーバーロードだけが選択されなくなり、関連するコンパイラテストでこの動作がカバーされれば完了です。

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

評価

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

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

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