microsoft / microsoft/TypeScript

Inferred type parameter does not satisfy constraint

Ouverte
#45,286 0 commentaires 6 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Bug Domain: check: Type Inference
Langage dominant
Go
Étoiles
111k
Forks
14.4k
Merge moyen
1 j 19 h
PR mergées (30 j)
117

Description

Bug Report

🔎 Search Terms

generic constraint, inference, invalid, specified, manually, explicitly, invalid

🕗 Version & Regression Information
  • This changed between versions 3.3 and 3.5
⏯ Playground Link

Playground link with relevant code

💻 Code
declare function f<T, U extends T>(cb: (u: U) => T): U

const v = f(u => "x");
// const v: unknown <-- wait, what?
// function f<string, unknown>(cb: (u: unknown) => string): unknown

f<string, unknown>(u => "x"); // error, of course
// -----> ~~~~~~~
// Type 'unknown' does not satisfy the constraint 'string'.
🙁 Actual behavior

In TS3.5+, the type parameter T is inferred to be string, and U is inferred to be unknown in the first call to f(). But then U extends T is not met; you couldn't even manually specify T and U like this when calling f(), as shown in the second call to f().

(In TS3.3, T and U are both inferred as {}.)

🙂 Expected behavior

Either I'd expect both T and U to be string, or I'd expect an error where the compiler says it cannot find a suitable candidate for U. Presumably the compiler has not inferred T before it needs to infer U, and so it constrains U to T's constraint which is implicitly unknown, and then falls back to that. But it never circles back to make sure that such a fallback actually works for U extends T.


I came upon this while looking for an answer to this SO question. This behavior is weird, right? I haven't found an existing issue for it.

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Reproduisez l’exemple TypeScript Playground lié et comparez le comportement signalé avec TypeScript 3.3 et 3.5+. Commencez par suivre l’inférence des types génériques et la vérification des contraintes pour les appels de fonction présentés. Le travail est considéré comme terminé lorsque le compilateur gère de manière cohérente la contrainte U extends T inférée et qu’une couverture de régression existe pour le comportement attendu sélectionné.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
typescript
Domaine
compilers
Type d'issue
Bug
Difficulté
5/5
Temps estimé
Plus d'une semaine
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
32/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.