feat(reactivity): enhance type inference for context-sensitive inputs #9516
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Close #1930.
Based on the issue description, I simplified the problem with the following code:
The error occurs due to context-sensitive type inference, specifically with the
b
property. The compiler defers type inference for thev
callback parameter until after inferring the generic type parameterT
. This leads to a fallback to inferT
from the expected return type ofBar
, a behavior introduced in microsoft/TypeScript#16072The use of a homomorphic mapped type
UnwrapNestedRefs<T>
further complicates inference, causingT
to be inferred fromBar
. This check succeeds for the return type but fails for thetarget
argument, resulting in an error.On the other hand, in this PR, the following code is provided:
In this case, the return type of
reactive
is still contextually typed fromBar
, butT
can now only be inferred from the value passed in astarget
. There was an old feature request at microsoft/TypeScript#7234 that would have supported such inference, but it hasn't been implemented yet.This behavior is sometimes used intentionally to block inference. There's an open feature request at microsoft/TypeScript#14829 asking for a way to prevent the use of a type parameter from being used as a generic type argument inference site. Although native support for this doesn't exist, one of the workarounds is to use
NoInfer
, as mentioned in this comment on ms/TS#14829.With the added overload function, similar scenarios can ensure that
T
is inferred from the function argument.