Skip to content

Narrowed union types loosened within closures #19683

Description

@myitcv

This could be a dup of #14748; they seem related

TypeScript Version: 2.7.0-dev.20171102

Code

See in playground

class A { 
    name: string;
}
class B { 
    age: number;
}

let x: A | B;

if (x instanceof A) {
    console.log(x.name); // ok: x has type A

    setTimeout(() => {
        console.log(x.name); // ** COMPILE ERROR: x has type A | B here
    });
} else {
    console.log(x.age); // ok: x has type B here

    setTimeout(() => {
        console.log(x.age); // ** COMPILE ERROR: x has type A | B here
    });
}

Expected behavior:

This should compile.

Actual behavior:

It does not compile

Activity

  1. ghost added
    DuplicateAn existing issue was already created
    on Nov 2, 2017
  2. myitcv commented on Nov 3, 2017

    @myitcv
    Author

    In my.situation (and indeed the repro) it is not possible for x to have been mutated, but I can see that in general case that's harder to work out definitively. Thanks for the const tip.

  3. locked and limited conversation to collaborators on Jun 14, 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

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions