Skip to content

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

Description

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

Activity

  1. normalser commented on Sep 14, 2016

    @normalser
  2. ahejlsberg commented on Sep 14, 2016

    @ahejlsberg
    Member

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

  3. ethanresnick commented on Sep 15, 2016

    @ethanresnick
    ContributorAuthor

    Got it. Thanks!

  4. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions