Don't widen return types of function expressions
See original GitHub issueThis change courtesy @JsonFreeman who is trying it out
(context elided: widening of function expression return types)
The problem with this widening is observable in type argument inference and no implicit any. For type argument inference, we are prone to infer an any, where we should not:
function f<T>(x: T, y: T): T { }
f(1, null); // returns number
f(() => 1, () => null); // returns () => any, but should return () => number
So after we get to parity, I propose we do the following. We do not widen function expressions. A function is simply given a function type. However, a function declaration (and a named function expression) introduces a name whose type is the widened form of the type of the function. Very simple to explain and simple to implement.
I’ve been told that this would be a breaking change, because types that used to be any are now more specific types. But here are some reasons why it would be okay:
- In the places where you actually need the type to be any (because there are no other inference candidates), you would still get any as a result
- In places where there was a better (more specific) type to infer, you’d get the better type.
- With the noImplicitAny flag, you’d get fewer errors because there are actually fewer implicit anys
Questions:
Is a principle of design changes going forward to not switch from ‘any’ to a more precise type because it can be a breaking change?
Going with ‘not a breaking change’ here because this is unlikely to break working code, but we need to verify this.
Would this manufacture two types?
In essence, we already have two types: The original and the widened type. So by that measure this is not really a change
Has someone tried it?
Jason willing to try it out and report back
Issue Analytics
- State:
- Created 9 years ago
- Reactions:77
- Comments:30 (11 by maintainers)
Top GitHub Comments
Hey everyone, I opened #40311 a couple of days ago which I think should fix most of the issues that have brought people here. If you’d like to give it a try, we have a build available over at https://github.com/microsoft/TypeScript/pull/40311#issuecomment-683255340.
Time to take this back up since it’s affecting a lot of people writing reducers