microsoft / microsoft/TypeScript

Inferred type parameter does not satisfy constraint

Abierto
#45,286 0 comentarios 6 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Bug Domain: check: Type Inference
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

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.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Reproduce el ejemplo enlazado de TypeScript Playground y compara el comportamiento informado con TypeScript 3.3 y 3.5+. Empieza rastreando la inferencia de tipos genéricos y la comprobación de restricciones para las llamadas a funciones mostradas. Se considera terminado cuando el compilador maneja de forma coherente la restricción U extends T inferida y existe cobertura de regresión para el comportamiento esperado seleccionado.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Error
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
32/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.