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

Variable type incorrectly narrowed to null when a callback is passed to a function #15380

Closed
tothdavid opened this issue Apr 25, 2017 · 1 comment · May be fixed by #58729
Closed

Variable type incorrectly narrowed to null when a callback is passed to a function #15380

tothdavid opened this issue Apr 25, 2017 · 1 comment · May be fixed by #58729
Labels
Duplicate An existing issue was already created

Comments

@tothdavid
Copy link

TypeScript Version: 2.2.2
Compile with StrictNullChecks enabled.

Code

class Foo {
    public bar: string = "";
}

function test() {
    let foo: Foo | null = null;

    [1].forEach((item) => {
        foo = new Foo();
    });

    // Here Typescript compiler incorrectly thinks that 'foo' has null type 
    // although it will always be an instance of Foo class.
    if (foo) {
        // The next line does not compile because 'foo' variable has never type here.
        foo.bar;
    }
}

Expected behavior:
Should compile.
Actual behavior:
Does not compile. The compiler incorrectly narrows the type of foo variable to null type as it seems to ignore the callback given to the forEach function call, which actually will always be called.

Notes:
The code compiles without StrictNullChecks just fine.
The below code works as expected, and I believe the same would be the expected behavior for the example code as well:

class Foo {
    public bar: string = "";
}

function test() {
    let foo: Foo | null = null;

    // When calling a simple lambda explicitly this works as expected
    (() => {
        foo = new Foo();
    })();
    if (foo) {
        foo.bar;
    }
}
@mhegazy
Copy link
Contributor

mhegazy commented Apr 26, 2017

Duplicate of #10982 and #10613. See #9998 for relevant discussion.

@mhegazy mhegazy added the Duplicate An existing issue was already created label Apr 26, 2017
@mhegazy mhegazy closed this as completed Apr 26, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
This issue was closed.
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

Successfully merging a pull request may close this issue.

2 participants