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

2.0: Type guards not working inside callbacks #7719

Closed
jeffreymorlan opened this issue Mar 29, 2016 · 2 comments
Closed

2.0: Type guards not working inside callbacks #7719

jeffreymorlan opened this issue Mar 29, 2016 · 2 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@jeffreymorlan
Copy link
Contributor

function f(x: {}) {
    if (typeof x === 'string') {
        x.charAt(0); // OK
        [1, 2].map(i => x.charAt(i)); // OK in 1.8, error in current master
    }
}

This appears to have started with commit dad0564

@Arnavion
Copy link
Contributor

The new behavior is correct, since TS cannot know when the callback will execute. Consider:

var x: {} = "a";
if (typeof x === "string") {
    setTimeout(() => console.log(x.charAt(0)), 0);
}
x = 5;

It is wrong to assume x is a string when x.charAt() is called, as indeed it isn't.

The fix is to bind it to a scoped local:

var x: {} = "a";
if (typeof x === "string") {
    let y = x;
    [1, 2].map(i => y.charAt(i));
    setTimeout(() => console.log(y.charAt(0)), 0);
}

@mquandalle
Copy link

mquandalle commented Jul 19, 2016

Also instead of scoped locals, we can use const. This works just fine:

function f(x: {}) {
    const y = x;
    if (typeof y === 'string') {
        y.charAt(0);
        [1, 2].map(i => y.charAt(i));
    }
}

Having to rename function parameters to use const is quite cumbersome though, I hope TS will provide a compiler parameter to assume const automatically for all functions parameters as suggested in #9491 (comment).

I even think that useConstParameters should be the default in TS 2.0; I realize it would be a breaking change, but basically this issue and the dozen of similar instances are also breaking changes—and quite serious ones, it breaks whenever we use a function parameter inside a callback, and the error message is confusing. I suspect the number of functions that re-assign their parameters symbols in their body is much lower, and that the error message would be way easier to understand.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants