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

Null inference of constants within callbacks #8880

Closed
ntrrgc opened this issue May 28, 2016 · 2 comments
Closed

Null inference of constants within callbacks #8880

ntrrgc opened this issue May 28, 2016 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@ntrrgc
Copy link
Contributor

ntrrgc commented May 28, 2016

TypeScript Version:

1.9.0-dev.20160528-1.0

Code

function printString() {
    const myString: string|null = 'Hello';
    if (myString == null) {
        return;
    }
    setTimeout(() => {
        console.log('String length was ' + myString.length);
    }, 100);
}
printString();

Actual behavior:

When compiled with --strictNullChecks, this code fails:

testcase.ts(7,44): error TS2531: Object is possibly 'null'.

Expected behavior:

Null inference works fine within the immediate printString scope, but it's disabled inside closures.

This behavior makes sense for variables, since otherwise I could write something like this, that would make myString actually become null when it's read and fail:

function printString() {
    let myString: string|null = 'Hello';
    if (myString == null) {
        return;
    }
    setTimeout(() => {
        console.log('String length was ' + myString.length);
    }, 100);
    myString = null;
}
printString();

On the other hand, constants don't allow this, so their non-nullity can be guaranteed if they were checked before the closure was declared.

@ivogabe
Copy link
Contributor

ivogabe commented May 28, 2016

This will be fixed with #8849

@ntrrgc
Copy link
Contributor Author

ntrrgc commented May 28, 2016

Cool! 😃

@mhegazy mhegazy closed this as completed Jun 7, 2016
@mhegazy mhegazy added the Duplicate An existing issue was already created label Jun 7, 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

3 participants