microsoft / microsoft/TypeScript

Generic recursive function infers incorrect return type

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

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

Bug
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
2日 4時間
マージ済み PR(30日)
132

説明

🔎 Search Terms

generic, recursive, return, infer

🕗 Version & Regression Information
  • This changed between versions 5.4.5 and 5.5.4
  • This bug continues to exist in nightly
⏯ Playground Link

https://www.typescriptlang.org/play/?ts=6.0.3#code/MYewdgzgLgBAZjAvDAPAFQDQD4AUBDALhkxgAciwBXAWwCMBTAJwEoksYBvAKBl5gEsEOAISlWjelEqMwMPAG4efCVJnwcpDGRgBaGAEZmXAL5cuoSLAAeSdQCI4IEHa0BWIxYggANvQB03iAA5jhWzEA

💻 Code
const f = <T,>(a: T, p: number) => {
    if (!p) return a;
    return f(p, p - 1) // f<number>
}

const x = f("foo", 5) // inferred type "foo"
console.log(x) // 1
🙁 Actual behavior

The compiler infers f's return type to be T. Then x is inferred to have type "foo" (or string), even though the actual return value is 1 (type number).

🙂 Expected behavior

In the example f is a recursive and generic function. Importantly, when recursing f calls itself on a non-generic type.

If p is falsy then f returns a, which has the generic type T. This is the "base case". However if p is truthy then f calls itself with type parameter number, so in all the recursive cases the return type is actually number.

So the actual return type of f should be T | number.

Additional information about the issue

In earlier versions of the compiler (I tested 5.4.5) recursive functions without explicit return type annotations are flagged as an error, so we sidestep this bug by requiring the return type to be manually declared:

'f' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. (7023)

In later versions however the compiler seems to think it can infer the return type, leading to this incorrect inferred result. Interestingly even though the compiler infers f to return type T, if we add the explicit return type annotation T then the compiler actually becomes unhappy (geez, make up your mind):

const f = <T,>(a: T, p: number): T => {
    if (!p) return a;
    return f(p, p - 1) // Type 'number' is not assignable to type 'T'.  'T' could be instantiated with an arbitrary type which could be unrelated to 'number'. (2322)
}

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

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

はじめの一歩

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

調査の方向性

リンクされている TypeScript Playground の再現例から始め、報告されているコンパイラーバージョン間で推論の挙動を比較します。再帰呼び出しが具体的な型を使用する場合に、再帰的なジェネリック戻り値の型がどのように推論されるかを追跡し、その後、この例のリグレッションテストを追加します。関数が T | number を返すと推論され、誤った推論結果が受け入れられなくなれば完了です。

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

評価

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

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

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