microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.26k stars 12.52k forks source link

Control flow analysis does not take effect of closure of inner functions into account #60554

Open jpilgrim opened 6 days ago

jpilgrim commented 6 days ago

🔎 Search Terms

literal types, arrow function definition, control flow closure

🕗 Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.8.0-dev.20241121#code/GYVwdgxgLglg9mABMAFFAXIgzlATjMAcwEpEBvAKEWsQBsBTKbTAIgEMXEAfRFgI04BeXhwDcVGhAQ5sYemwDWiYSlKCAfOQk0aWZbwHidAX22IYwRGmWDh-FqUo6dWOYtVGapnRat7bdgKOZjq4jCC4SHgg9J7U3jRhUBFIwGy0WLEUxkA

💻 Code

function f(t: string) {
    let s: "a" | "b" = "a";
    const sneak = () => {
        s = "b";
    }
    if (t === "b") {
        sneak();
    }
    if (s === "b") { // <--- here should be no error!
        return true;
    }
    return false;
}

🙁 Actual behavior

In the line marked with a comment, an error is issued: This comparison appears to be unintentional because the types '"a"' and '"b"' have no overlap.

🙂 Expected behavior

No error should occur here.

Additional information about the issue

In the example, the control flow analysis apparently does not recognise the effect of the inner function definition or its behaviour when computing the actual type of the variable s. This also happens in case of union types, for example. And it also happens for nested function declarations.

Andarist commented 6 days ago

https://github.com/microsoft/TypeScript/issues/9998

jpilgrim commented 3 days ago

@Andarist Thanks for the link! I did search for bugs, not for discussions...

Well, the discussion is still open. And I run into that problem again and again. I would consider it a bug (or simply too optimistic).