Skip to content

Type Gaurds Don't Narrow Type in Inner Functions #10927

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
ethanresnick opened this issue Sep 14, 2016 · 3 comments
Closed

Type Gaurds Don't Narrow Type in Inner Functions #10927

ethanresnick opened this issue Sep 14, 2016 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@ethanresnick
Copy link
Contributor

TypeScript Version: 2.0.2

Code

  function isNumber(test: number|string): test is number {
    return typeof test === "number";
  }
  function blah(arg: () => void): void { }

  let x: any = 4;

  if(isNumber(x)) {
    x; // x is correctly narrowed to number here
    blah(() => {
      x; // typeof x is any again
    })
  }

Expected behavior:
(I think) x should still be inferred as type number in the inner function.

Actual behavior:
x is inferred as any

@normalser
Copy link

#7719 (comment)

@ahejlsberg
Copy link
Member

FYI, it works as expected if you use const instead of let because the compiler then knows that x will never be reassigned.

@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label Sep 14, 2016
@mhegazy mhegazy closed this as completed Sep 14, 2016
@ethanresnick
Copy link
Contributor Author

Got it. Thanks!

@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
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants