Inferring a generic should put the type variable in the inner scope when possible #49505
Open
5 tasks done
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
Suggestion
π Search Terms
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
When inferring a generic type, put the type variable in the inner scope as long as it's possible to make the result as general as possible.
π Motivating Example
Say I have a simple composition function:
The current version of TS allows me to do this and get the correct type:
But say I want to wrap the result in an object:
Now the generic is gone, and
comp
above is typed as{ value: (a: unknown) => unknown }
.I think what's happening is that TS is trying to put the
T
variable outside the scope of the object because if, instead of a wrapping object, I use a wrapping function, this is what happens:TS is putting
T
on the outer level, so if I callcomp()
the result will be(a: unknown) => unknown
. A better result would've been to get() => <T>(a: T) => T
. This way, callingcomp()
would not discard the type variable and, if I'm not mistaken, the result would be a more general type than the result we currently get, without breaking any typing rules.π» Use Cases
Being able to wrap generic functions when they're the result of type inference. My specific case was writing a type guarding/converting utility using a wrapper around functions of the form
a -> Maybe<b>
that can be chained together by the dot operator to represent function composition, such that types can be further specified. Something likeThing.isPrimitive.isNumber.isInteger
. But this is not possible without the possibility to wrap the result of mycompose
function.The text was updated successfully, but these errors were encountered: