microsoft / microsoft/TypeScript

Correlated type constraint breaks under return type inference

Abierto
#32,804 6 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Discussion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.3k
Merge medio
2 d 4 h
PR fusionados (30 d)
132

Descripción

TypeScript Version: 3.5.1

Search Terms:

return type, generic, constraint, assignable, correlated type

Code


type XStr = {x:string};
type XNum = {x:number};
type U = XStr|XNum;
type Args = { str : XStr, num : XNum };

declare function foo<
    ReturnT extends U,
    ValueT extends ReturnT["x"]
> (
    f : (args : Args) => ReturnT,
    value : ValueT
) : void;

/*
    Error as expected.

    Type 'string | number' does not satisfy the constraint 'string'.
    Type 'number' is not assignable to type 'string'.
*/
foo<XStr, string|number>(
    (args:Args) => args.str,
    ""
);
//Inferred type, foo<XStr, string | number>
foo(
    args => args.str,
    //Expected: Error
    //Actual: OK
    "" as string|number
);
//Inferred type, foo<XStr, string>
foo(
    //Added explicit type annotation to function params
    (args:Args) => args.str,
    /*
        Error as expected.

        Type 'string | number' does not satisfy the constraint 'string'.
        Type 'number' is not assignable to type 'string'.
    */
    "" as string|number
);

/////

/*
    Error as expected.

    Type '1' does not satisfy the constraint 'string'.
*/
foo<XStr, 1>(
    (args:Args) => args.str,
    1
);
//Inferred type, foo<XStr, 1>
foo(
    args => args.str,
    //Expected: Error
    //Actual: OK
    1
);
//Inferred type, foo<XStr, string>
foo(
    //Added explicit type annotation to function params
    (args:Args) => args.str,
    /*
        Error as expected.

        Type '1' does not satisfy the constraint 'string'.
    */
    1
);

Expected behavior:

I'm just calling it a correlated type because it reminds me of correlated subqueries from SQL.

  1. The constraint type of ValueT is dependent on the type of ReturnT.
  2. When f does not have parameters, or all parameters are explicitly annotated,
    ValueT is inferred correctly.
  3. When f has parameters that are not explicitly annotated,
    ValueT is inferred incorrectly.
  4. Attempting to explicitly set invalid type paramters will error as expected.
  • foo<XStr, string|number> should not be allowed
  • foo<XStr, 1> should not be allowed

Actual behavior:

  • foo<XStr, string|number> is allowed under inference
  • foo<XStr, 1> is allowed under inference

Playground Link:

Playground

Related Issues:

https://github.com/microsoft/TypeScript/issues/32540#issuecomment-520193240

https://github.com/microsoft/TypeScript/issues/29133

A different, more complex example,
https://github.com/microsoft/TypeScript/issues/14829#issuecomment-520191642


[Edit]

Can someone come up with a better name for this?


I'm working on rewriting my type-safe SQL builder library and it relies on the return type of generic functions being inferred correctly. But it seems like return type inference just breaks in so many unexpected ways.

Anonymous callback functions are used a lot for building the WHERE, ORDER BY, GROUP BY, HAVING, JOIN, etc. clauses.

Since return type inference for generic functions is not robust, it's basically a blocker for me =(

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

Comienza con la reproducción en TypeScript Playground del issue y compárala con los issues relacionados 32540, 29133 y 14829. Sigue la inferencia de los tipos de retorno genéricos y de las restricciones; se considera terminado cuando las llamadas inferidas rechacen string|number y 1 en los casos mostrados, mientras que la inferencia válida de string siga siendo aceptada.

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
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.