Description
TypeScript Version: 3.7.2 and 3.8.0-dev.20191123
Search Terms: Inference, generic function, unknown, argument not assignable, type parameter
Code
type Foo<T> = (t: T) => T
const increment: Foo<number> = x => x + 1
declare function acceptFoo<T>(foo: Foo<T>): void
acceptFoo(increment) // Works
declare function acceptFoo2<T, F extends Foo<T>>(foo: F): void
acceptFoo2(increment) // Error, argument not assignable to Foo<unknown>
// Work-around: explicitly intersect F with its bound
declare function acceptFoo3<T, F extends Foo<T>>(foo: Foo<T> & F): void
acceptFoo3(increment) // Works
Expected behavior:
Inference results in T
being number
, not unknown
. No type error at acceptFoo2
call site.
Actual behavior:
T
is unknown
, causing a type error.
Note that if Foo were covariant in T, not invariant (as in this case) or contravariant, the above code would type-check, but the poor type for T could still be impactful, for example if T were part of the return type of acceptFoo
. It's fortunate that the above work-around, using an intersection, is available. Without that, you'd have to specify all type parameters at the call site, because TypeScript doesn't yet support specifying some type parameters and inferring the rest. I am creating some APIs where it would be very inconvenient for the user to explicitly write out all the type parameters that would be inferred.
For some reason I thought TypeScript's inference was smart enough to go through one type parameter to another, but I tried this code on versions back to 2.8.1 and the result is the same.
Related Issues:
Possibly related to #35288, which is about inference not taking advantage of the fact that a class Foo extends interface IFoo.