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

Type narrowing not scope aware #10339

Closed
ithinkihaveacat opened this issue Aug 15, 2016 · 3 comments
Closed

Type narrowing not scope aware #10339

ithinkihaveacat opened this issue Aug 15, 2016 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@ithinkihaveacat
Copy link

TypeScript Version

2.0 (installed via npm install typescript@2)

Code

function foo(x: number|string): number {

  if (typeof x === "string") {
    x = 1;
  }

  function bar() {
    return 1 + x;
  }

  return bar();
}

Expected behavior

Code compiles cleanly.

Actual behavior

Compiler complains Operator '+' cannot be applied to types 'number' and 'number | string' (within function bar()).

@JannesMeyer
Copy link

I am just a TypeScript user myself, but this is much more complex than you might think, because function bar is hoisted to the top of the scope before your if:

function foo(x: number|string): number {

  function bar() {
    return 1 + x;
  }

  if (typeof x === "string") {
    x = 1;
  }

  return bar();
}

@ithinkihaveacat
Copy link
Author

Yes, true. I realize this is a slightly tricky case, but I think this type error/warning is bogus: x can only be a number within bar(), and I got the impression from the docs that TS 2.0 (though not 1.8) is supposed to know this.

@yortus
Copy link
Contributor

yortus commented Aug 15, 2016

TypeScript does not reach that level of control flow analysis (yet). See also #7719 and #10180.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 15, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
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