-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Infer type of simple recursion #55342
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Duplicate #3336 |
Relevant part from the linked issue:
I think any implementation with special rules as outlined by OP is way too complex for the small benefit. Just add a type annotation. |
According to that issue:
I think the resolution is as simple as changing |
This wouldn't work, and would be dangerously unsound. It'd imply you could write code like function self() {
const arr: string[] = [];
arr.push(self()); // OK, self() returns never here, and never subtypes string
return 3 * (Math.random() > 0.5 ? self() : 2);
} |
You actually can write code like that with |
I presume you mean something like this.
When performing inference, yes, you'd allow the above code, and you'd infer that It similar in spirit to this, which has no trouble inferring the type of
|
Checking and resolving types are done in the same pass. See the conversation in #45213 where this was discussed at length with another contributor. |
@RyanCavanaugh Thank you! #45213 sheds a lot of light. I had assumed the overall checking algorithm was some sort of iterative constraint solver, that is:
It hadn't even occurred to me that the checker is doing structural recursion instead of iterative constraint solving! @MartinJohns, @fatcerberus I guess you could call this a duplicate of #3336, but it's hard to say. The discussion has scant detail, and the motivating example was fixed by #53995. |
π Search Terms
recursive, never, implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
β Viability Checklist
β Suggestion
With recursive functions, it is often possible to infer the return type without function annotations.
If all return statements have inferrable type, it would be nice to use their union as the return type of a function (even if that function is recursive)
Similar to Ignore self tail calls when collecting the return type of a functionΒ #53995, you can assume in the body of a recursive function that any recursive call with unchanged argument types returns type
never
.π Motivating Example
Workbench Repro
π» Use Cases
TBD
The text was updated successfully, but these errors were encountered: