Repository: TypeScript
Issue: Correlated type constraint breaks under return type inference
Labels: Discussion

<!-- 🚨 STOP 🚨 𝗦𝗧𝗢𝗣 🚨 𝑺𝑻𝑶𝑷 🚨

Half of all issues filed here are duplicates, answered in the FAQ, or not appropriate for the bug tracker. Even if you think you've found a *bug*, please read the FAQ first, especially the Common "Bugs" That Aren't Bugs section!

Please help us by doing the following steps before logging an issue:
  * Search: https://github.com/Microsoft/TypeScript/search?type=Issues
  * Read the FAQ: https://github.com/Microsoft/TypeScript/wiki/FAQ

Please fill in the *entire* template below.
-->

<!-- Please try to reproduce the issue with `typescript@next`. It may have already been fixed. -->
**TypeScript Version:**  3.5.1

<!-- Search terms you tried before logging this (so others can find this issue more easily) -->
**Search Terms:**

return type, generic, constraint, assignable, correlated type

**Code**

```ts

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](http://www.typescriptlang.org/play/#code/LAKALgngDgpgBADQMpgE5wLxwN4A8BcAzmgJYB2A5gL4DcoksiAcgK4C2mOBZ7ARjKlr1o8AKqdkaAD4JWbOuBFwAgqgqFO2OMXT5EKVABo4PDntns4QkKAAmMAMYAbAIap4AMxZkHYEgHsyOA9-fwAeUDgouAAlGDAWVDIAFTgYXDAYMlsNUUNI6IA1FycWGFT0zOyNOISk5IBtACJcJoBdUAA+OAAKAqiPOD0et3UhlTVCAEpMbtrElPyQaLgANxKy8eLS8tAZvVX-ElsFUAB6ACp+uABRVFR-dBcNdNhfGFsAOlBr5KUAch05AocCkJj4An+cFs-hgGjI-jA2hcfkIHggcDAAAt4A5AjoXOQkYDSJR-t9ltE-ox-qZ+KgoSR4Yi4M9CCQKGQXLwnPAwP5MQCgWSKRczqAQuFJEZtKSKFI6QJOn1KVERpN8Kp1DMMN1RoRPjolismk09gozmcAJJkDwCdy2QWwYySsLS4zCkFgxWoToS0Iqlb62asyaGtDG6KWm64N6ZWx6O4PVDXS3KXwsEp6ADyAGlrqbWRpPQqISmQFMLdbbfaPk6YC7Qm6DB65X6QJLA1GzspbPZHa8nCQHCQkQx4C4yAiwCiAkF+cFvL453AoG4XGxCNd1epNZMdXqw0bU1dVStbvdHkW0rHHPGKdcVtT4CTUMDQeC2PSoTC4SYWYQs5ohi2K4viaCEmQxKeuSj5UgCPqMsySJshyXI8nyArjnAr7ArBZ5igWTTXiWPrmj8ICWlRFGXNcSZXs8N5xh8D5ns+OEAIw-rCyHIqi6KYjicB4mQBJEjhMGiuKHZNu6cAccq276nu2ohvq4ZGNcHHkZR1Z2vcdbjo2UotvJ7adtcwa6qG6gaZGUTRre7wJheyapj2GZZnAeZaTplo2vpDr1sZzYRrKb6UOZAbub2-ZMUOI5jkok7TrOgSYgKXg+H46VrqgG5bmeO6ECp0xqUeEYnnBUT0U8LxOfeFHnvBNJcdCPH-kigH8SBQkiWJUESXK+ErIRZ7aRWChAA)

**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 =(