microsoft / microsoft/TypeScript

Generic recursive function infers incorrect return type

Aperta
#63,990 1 commento 2 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Bug
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

🔎 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)
}

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia dalla riproduzione collegata in TypeScript Playground e confronta il comportamento dell'inferenza tra le versioni del compilatore indicate. Traccia come vengono inferiti i tipi di ritorno generici ricorsivi quando la chiamata ricorsiva utilizza un tipo concreto, quindi aggiungi un test di regressione per questo esempio. Il lavoro è completato quando la funzione viene inferita come restituita da T | number e il risultato inferito errato non viene più accettato.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Attiva
Chiarezza
Abbastanza chiara
Idoneità per principianti
52/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.