Skip to content

Ambiguous scoping of if statement body #60175

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

Closed
acutmore opened this issue Oct 9, 2024 · 1 comment Β· Fixed by #60183
Closed

Ambiguous scoping of if statement body #60175

acutmore opened this issue Oct 9, 2024 · 1 comment Β· Fixed by #60183
Labels
Bug A bug in TypeScript Help Wanted You can do this
Milestone

Comments

@acutmore
Copy link
Contributor

acutmore commented Oct 9, 2024

πŸ”Ž Search Terms

type, scoping, ifStatement

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type scoping

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.6.2#code/GYVwdgxgLglg9mABMAjACgJSIN4ChEGIzCJpQBOIAphvoYVAJ4AOViAzogLwcUxgBzANx16iCAnZwANlQB00uALQAiFYgCGndhhH1cAX1y5QkWAmQAmTDlFESZSjVtj6TVh269y-YXaP0EmBSsgpKqupaHLqGuEA

πŸ’» Code

function f1() {
    if (true)
       type s = string;
       console.log("" as s);
}

function f2() {
    if (true) {
         type s = string;
    }
    console.log("" as s);
}

πŸ™ Actual behavior

From type-system perspective in the first if it appear that the console.log is part of the body of the if because the type is in scope. However the JS emit is:

function f1() {
    if (true)
        ;
    console.log("");
}

So the console.log is not part of the if body.

πŸ™‚ Expected behavior

function f1() {
    if (true)
       type s = string;
       // @ts-expect-error : "cannot find name 's'"
       console.log("" as s);
}

Also happy for this to be a parse error. An if statement with only a type declaration as a body hopefully has no use cases.

Additional information about the issue

No response

@RyanCavanaugh
Copy link
Member

Parse error seems like the best option; we can use the same logic that disallows

if (true) let n = 3;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Help Wanted You can do this
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants