Skip to content

Recursive functions are inferred to have return type any #3336

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

Closed
fsoikin opened this issue Jun 2, 2015 · 1 comment
Closed

Recursive functions are inferred to have return type any #3336

fsoikin opened this issue Jun 2, 2015 · 1 comment
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead

Comments

@fsoikin
Copy link

fsoikin commented Jun 2, 2015

Consider this code:

function fact( x: number, acc?: number ) {
    if (x <= 1) return acc;
    else return fact( x - 1, (acc||1)*x );
}

var res = fact( 5 );

(same thing on playground)

Here, fact is inferred to have type (number, number?) => any, and consequently res is inferred to have type any.
This is vaguely reminiscent of cases #1146, #475, and #523, but those deal with some esoteric circumstances, while this here is a textbook case of a tail-recursive algorithm. Should work.

Note: no, it doesn't have to do with optional parameter, I checked.

@RyanCavanaugh RyanCavanaugh added the By Design Deprecated - use "Working as Intended" or "Design Limitation" instead label Jun 2, 2015
@RyanCavanaugh
Copy link
Member

We briefly had a spec that outlined how this could all work in theory (the term "witnessing" used in #402), but it didn't make it to implementation.

The current rule is that any function that sees itself during the resolution of its return type is any. This seems to be good enough in practice, since it's always possible to add the needed type annotation and most functions aren't recursive like this due to tail call optimizations not being part of the ES spec yet (watch that stack!).

Unless some use cases become super compelling in terms of complexity vs gain, we don't foresee changing this for the sake of eliding one type annotation.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead
Projects
None yet
Development

No branches or pull requests

2 participants