Skip to content
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

Control flow analysis based on operators applied to an argument #15196

Closed
mohsen1 opened this issue Apr 14, 2017 · 2 comments
Closed

Control flow analysis based on operators applied to an argument #15196

mohsen1 opened this issue Apr 14, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@mohsen1
Copy link
Contributor

mohsen1 commented Apr 14, 2017

TypeScript Version: 2.2.1 /

Code

function foo(a) {
  return a * 2
}

foo(''); // Flow throws an error but TypeScript marked foo as foo(a:a ny): number;

Expected behavior:
a is type number
Actual behavior:
a is type any

Try in Flow REPL

Try in TypeScript REPLE

@aluanhaddad
Copy link
Contributor

discussion and rational
#1265
related
#15114
#11440

@mhegazy
Copy link
Contributor

mhegazy commented Apr 17, 2017

I have a PR to add a quick fix to infer the type as number from such cases in #14786.

Inferring from call sites is something we have decided not to pursue for the TS compiler since its inception, and there are multiple reasons. For example, what if the function is not called? What if the use is in another compilation? What if the call is the error, and not the function declaration? What if the calls in your tests, are not exhaustive?

Moreover, this approach really works for a small snippets of code but does not scale specially with IDE scenarios and you want to know what changing one name mean for the whole compilations. Systems we have seen that take this approach either limit the inference to one file to make it more manageable, or do not care about accuracy.

We believe that type annotations serve better when added to declarations rather than non-local use sites for inference; they help readability and allow tools to correctly check for the user-intended behaviors. Using noImplicitAny to mark locations TypeScript could not figure out types in other locations helps ensure the experience stays consistent and prescriptive.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants