microsoft / microsoft/TypeScript
Don't widen return types of function expressions
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
This 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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the two generic-call examples and checking their inferred types, including behavior with noImplicitAny. Done means function expressions retain their specific function types, while function declarations and named function expressions expose widened types, with inference and compatibility verified.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100