Repository: TypeScript
Issue: Covariant quantifiers are specialized to widest possible type in conditional types, should be narrowest
Labels: Suggestion,In Discussion

### 🔎 Search Terms

Generics, variance, conditional types, inference

### 🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about conditional types (specifically the note about falling through to `never` and "distributive conditional types", which is not what's happening in my example)

### ⏯ Playground Link

[Playground link with relevant code](https://www.typescriptlang.org/play?target=99&ts=4.2.0-beta#code/C4TwDgpgBAYghgSwDYB4C2BnA5lCAPYCAOwBMMoNgAnBIrAPigF4oBvXKqgeyoC4pMWADRQEaOFlpwqIfkQgA3CFSgBfAFChIUALIICAVyoQA8gDMUVRiyoBtANYQQXM1CoBdTeGgA1aQjgiYHNLa119YCNTC3YHUSIoR2dXD352YAl+exEFOCQDCH47e3c1NXp1dQB6KqgAQSgtaABjLiJKKgNm4B4oAHcEYAALKDgoACpW3JpA4HHG7ygwaTg0CEIqL20AFSGDInsULjCACgBKZkZjOBI2pBAoLltPatqAZS413DxVsCQIDDqVrtYAUai0LC7fb2fhQg4oDoQ04XJiMWwAIjMXC46JE6IARtJ0Z5gZQoEQDGh8co4TCoLSUBSqcpkZcoLYAIwiABMJLaZLAXHutP4KDg9HObOutyI91Gz2YUElqPZpRq9KGCHIbWgWqWQpAaB4YE1zQAhJUmvTlGgpEhaYqGdCiFw+kRGOqYL1Ag88CIxgy8Iw9XAMBgEFgiHB8f9GlxrVRbVH7XsDkD+aCMJ8ILSMEUIDc7g9tja7bSFSxbILhansmCaHRaSImdSqLSXlaAJJEQYBFPQx21xmKFlQT3eoi+-0Jbu9vIOkNhiNRmPQHoa6EoIPpkHxOf9g78WfAPsOljVkC0ndk4YQOpIA90poufU1gcAMgWkBfiMbtagn7Pq4LY0v+LC0PuV6vFAADqLSBFABgYNAYwnCQWrgviBgnkoFzAuhJ5tHkX5rvG+DUHA3SNEMa6LMsVCrOsyiPK4Aa1ls0AmNhYDYSEwzQmE-EHN8hCkOQDK0GYzFBlAAD8UB4FA-DwMgKAAOR9EM2JgBgakVOqAB0RmjKQcYiQxVG3iRSwrGsGzaqx5KUq2LEbgcgJWlxwA8cAGB8bWGBhLE9jxIkTgvkJ9gYO4-BeT5-nQhgDjuIwGjQXBakkFASAII4ZnUqMq5mX0PAhQMwzUdAGCUq5VknFM-izBc9GMfZrljCBKgvgyAD6jBNBgIhZl8L6aQgzQjOIDwFReRpUCa40GRxUCtA+EBUSwKCReQ5HEGQUAAErrTwJAIuCdAiCWiZlrW9AStt-DbSijAMnohjGCEcXYX5FjbXdFSkqCq3-N0-DA+toIsNtbLKhUUBjrUAACvkALTLjwEDqPDJj4gAVhDBm5PkAInE9BlmEgcDADocBgCcChsgo5xnJU6rdlJnAQFloZuYcb2RB9Fhfb5IRGQZ-3XqChCUByirg90JzsL+kK1s2zmgQOqgs4DjQAsAHI9fmhayg8JzK1AAA+TnMlQZwVrrMuSuqADi2IkBa0Hs8oxjc+Q0pFohBwum6zySw7wDcnLQog8Aiuvpeqv1hCTbW62Dpa2H0sR4bbgFjKcpm+dOBW51dulFDevck7tQAEI3Ga9KLGp-sm4H9jB0QzxqaI5AuqCobhpG0axuuVrN3nAeFw2xep8oZdqUt0G7NAnRBGIK8AgYSC+aMxiiCQxAns0eTXkKEAGUgXBYKTescszp--BfV835QVdnGcQA)

### 💻 Code

```ts
type Fail<msg extends string> = { error: msg, imaginary: never }
type MixtureOf<r> = r[keyof r]
type VariantOf<r> = MixtureOf<{ [k in keyof r]: { tag: k, value: r[k] } }>

// A type constructor with a *covariant* type parameter
type Thunk<o> = () => readonly o[]

// Some examples
const stringThunk: Thunk<string> = () => ["foo", "bar"]
const numberThunk: Thunk<number> = () => [1, 2]
const polyThunk: <a>() => readonly a[] = () => [] // This one is polymorphic!

type TerminalThunk = Thunk<unknown> // For any x, a Thunk<x> is assignable to TerminalThunk
const someThunks: readonly TerminalThunk[] = [polyThunk, stringThunk, numberThunk]

type InitialThunk = Thunk<never> // For any x, an InitialThunk is assignable to Thunk<x>
const initialThunk: InitialThunk = polyThunk
const theAllThunk: typeof polyThunk & typeof stringThunk & typeof numberThunk = initialThunk

// We can use a (distributive) conditional type to extract the type parameter of a Thunk
type OutputOf<thunk> = thunk extends Thunk<infer x> ? x : Fail<'whoops'>
// ... and to extract the type parameters of a number of Thunks
type OutputsOf<thunks> = { [k in keyof thunks]: OutputOf<thunks[k]> }

// We'd like to be able to work with the sum of the (covariant) parameters of a number of Thunk<_> types, some of which may be polymorphic.
type collect = <thunks extends Record<string, TerminalThunk>>(thunks: thunks) => Thunk<MixtureOf<OutputsOf<thunks>>>
const collect: collect = thunks => () =>
  // @ts-ignore
  Object.values(thunks).flatMap(v => v())

// Inferred as Thunk<MixtureOf<OutputsOf<...>>>
const test1 = collect({ stringThunk, numberThunk })
const test1_: readonly (string | number)[] = test1() // Good!

// Inferred as readonly unknown[]
const test2 = collect({ polyThunk, stringThunk, numberThunk })
const test2_: readonly (string | number)[] = test2() // Bad! Type 'readonly unknown[]' is not assignable to type 'readonly (string | number)[]'.

// The runtime results are identical
console.log(test1())
console.log(test2())
```

### 🙁 Actual behavior

The assignment failed with the type error:

```
Type 'readonly unknown[]' is not assignable to type 'readonly (string | number)[]'.
  Type 'unknown' is not assignable to type 'string | number'.
    Type 'unknown' is not assignable to type 'number'.(2322)
```
### 🙂 Expected behavior

I expect the assignment in `test2_` to succeed without any further type annotation.

I'm not completely certain, but I suspect the problem arises from the fact that `OutputOf<typeof polyThunk> = unknown`, which is then summed with and absorbs `string` and `number` (due to `MixtureOf`).

As near as I can figure out, for covariantly quantified generic functions, a (distributive) conditional type seems to simply specialize all the quantifiers to their respective upper bounds before unifying with the RHS of the `extends` operator (the default upper bound being `unknown`). So for example:

```
type Test0 = OutputOf<<x extends unknown>() => readonly x[]> // Test0 = unknown
type Test1 = OutputOf<<x extends string>() => readonly x[]>  // Test1 = string
type Test2 = OutputOf<<x extends number>() => readonly x[]>  // Test2 = number
```

But even this rule doesn't seem to hold in general, :shrug: :

```
type Test3<ub> = OutputOf<<x extends ub>() => readonly x[]>  // Test3<ub> = unknown ???
```

Regardless, at least in the special case of unbounded covariant quantifiers, does it make any sense to instead produce `never`? I haven't thought about it super hard, but since all of TypeScript's inference problems are in "positive position" (i.e. you never try to infer the types of parameters), it seems like specializing any generic function to the narrowest possible type would do something good.

Cue the counterexamples of where this is nonsense...