How does Typescript generic auto-inferrence really works on multiple generics? [duplicate]

18 hours ago 1
ARTICLE AD BOX

TypeScript either infers all type parameters for a function, or you supply all of them explicitly. There is no middle ground of "infer some, I'll provide others."

b<User>({name: 'string'}) fails because when you write b<User>(...), you are entering explicit type argument mode. TypeScript now expects you to provide every type argument for that function, it won't infer the remaining ones. Since b has two type parameters <T, U>, it demands both:

b<User, Partial<User>>({name: 'string'}) // works, but defeats the purpose

This is by design. The TypeScript team has explicitly decided not to support partial type argument inference in a single call (see microsoft/TypeScript#26349), because the rules for which parameters get inferred vs. provided would be ambiguous and hard to reason about.

As for:

function b<T>() { return function<P extends Partial<T>>(p: P) { return p } } b<User>()({name: 'string'})

The current version works because you are now making two separate function calls, each with their own independent inference context:

b<User>() - you explicitly provide T = User for the outer function. This returns a new function whose signature is now concretely <P extends Partial<User>>(p: P) => P.

({name: 'string'}) - TypeScript infers P fresh for this second call from the argument you pass. No explicit type argument is given, so inference runs freely.

The two calls never compete - each one is either fully explicit or fully inferred on its own.

Read Entire Article