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

Simple non-nullability detection for closure variables #21195

Closed
yahiko00 opened this issue Jan 16, 2018 · 3 comments
Closed

Simple non-nullability detection for closure variables #21195

yahiko00 opened this issue Jan 16, 2018 · 3 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@yahiko00
Copy link

yahiko00 commented Jan 16, 2018

Code

function foo() {
    let icon = document.getElementById("icon");
    if (!icon) return;
    // From here, the local variable icon is defined and not null
    icon.addEventListener("click", () => {
        let bar = icon.id; // error TS2531: icon is possibly null
    }, true);
}

Expected behavior:
In the code above, the local variable icon cannot be null after the if statement, unless I miss something. Although there is a closure in the addEventListener call, and this is an asynchronous function, I fail to see how and when such a variable icon could be null since there is no other reference to this variable until the end of the function foo. I am wondering how difficult it would be to check the non-nullability of closure variables in such a simple case. This would prevent some useless errors/warnings and would avoid the usage of the ! operator.

Actual behavior:
The compiler emits an error TS2531: Object [icon] is possibly null

@mhegazy
Copy link
Contributor

mhegazy commented Jan 17, 2018

declare icon as const instead. see #21162.

@mhegazy mhegazy added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jan 17, 2018
@yahiko00
Copy link
Author

Alright, for my use case, this workaround is enough. Although, I suspect one could need to declare some variables (let) in some specific cases.

@ghost
Copy link

ghost commented Jul 1, 2018

How about if icon is an argument of the function, e.g. foo(icon: HTMLElement): void ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants